Click here to Skip to main content
15,907,913 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
PHP array is not working when I use a string php variable


What I have tried:

<?php
$x = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
$z = array($x);
echo $z[2];
?>
No Result
But when I tried:
<?php
$z = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
echo $z[2];
result: 3 
Posted
Updated 1-May-20 8:17am
v2

1 solution

You have to split the string by delimiter(, in this case). One of the best-known methods is using preg_split function which splits the string by specified delimiter and returns the split string as elements of an array.

PHP
<?php
$x = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
$z = preg_split ("/\,/", $x);
print_r($z);
?>
The output of the above code will be:
PHP
Array
(
    [0] => 1
    [1] =>  2
    [2] =>  3
    [3] =>  4
    [4] =>  5
    [5] =>  6
    [6] =>  7
    [7] =>  8
    [8] =>  9
    [9] =>  10
)
 
Share this answer
 
Comments
Member 14819235 1-May-20 14:24pm    
Perfect, I really appreciate your help, thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900