php – Array value from variable-ThrowExceptions

Exception or error:

Could somebody explaind me ***why array count is not 2

$value = '"305", "112", ';
//remove last comma and space
echo $value = rtrim($value, ', ');
echo '<br>';

$value = array($value);

echo $array_length = count($value); //***
How to solve:

you can use explode() to get it.

$value = '"305", "112", ';
//remove last comma and space
echo $value = rtrim($value, ', ');
echo '<br>';

$value = explode(',',$value);

echo $array_length = count($value); 

Answer:

You should use explode function to get array like the following code :

$value = '"305", "112"'; 
        $value = rtrim($value, ', ');
        echo '<br>';
        $value = explode(',',$value); 
        echo $array_length = count($value); 

Answer:

you can also do this if you want to create an array from that these type of strings and do array count.

$arr = array_filter(array_map('trim', str_getcsv($value)));
print_r($arr);
echo count($arr);

Answer:

when you are creating an array with array($value), the entire value of $value counted as a single element of an array. Thats why you are getting count($value) not equal to 2.

Leave a Reply

Your email address will not be published. Required fields are marked *