split function is not working anymore in php 8.2, is there any alternative function ?
split($users,"\n")
split function is not working anymore in php 8.2
Or, if you want to use a regex: preg_split()
- Edited
<?php
//-i means ignore case
$users = `grep -i smith /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/phonenums.txt`;
//split the output lines into an array
//note that the \n should be \r\n on Windows;
$lines = preg_split("/\n/",$users);
foreach ($lines as $line){
//name and phone nums are separated by, char
$namenum = preg_split(',',$lines);
echo "Name: {$namenum[0]},Phone #: {$namenum[1]}<br/>\n";
}
?>
in the file phonenums.txt
there is
smith,699457830
albert,34678912
Fatal error: Uncaught TypeError: preg_split(): Argument #2 ($subject) must be of type string, array given in /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/executing-commands.php:11 Stack trace: #0 /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/executing-commands.php(11): preg_split(',', Array) #1 {main} thrown in /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/executing-commands.php on line 11
the path is correct is working with the linux terminal
grep -i smith /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/phonenums.txt
return smith,699457830
$namenum = preg_split(',',$lines);
// should be...
$namenum = preg_split(',',$line);
...since presumably at that point you want to split the line you are looping on.
- Edited
Name: smith,Phone #: 699457830
Warning: Undefined array key 1 in /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/executing-commands.php on line 12
Name: ,Phone #:
<?php
//-i means ignore case
$users = `grep -i smith /var/www/html/php-books/php-and-mysql-web-development/chapter15/executing-commands-pag-353/phonenums.txt`;
//split the output lines into an array
//note that the \n should be \r\n on Windows;
$lines = preg_split("/\n/",$users);
foreach ($lines as $line){
//name and phone nums are separated by, char
$namenum = preg_split('/,/' ,$line);
echo "Name: {$namenum[0]},Phone #: {$namenum[1]}<br/>\n";
}
?>
this warning is because only return smith, is there any option to hidden this warning ?
I should use one if
if(isset($namenum[0]) and isset($namenum[1])){
echo "Name: {$namenum[0]},Phone #: {$namenum[1]}<br/>\n";
}
If you only want to output it if you have at least two elements, you could use count()
for the condtion:
if(count($namenum) > 1) {
// output it
}