how to make a php array [closed]
I tried transfer $str
to be an array group.
$str = '1,2,3,4,5';
print_r(array($str)); //this get Array ( [0] => 1,2,3,4,5 )
I tried compact
print_r(array(compact($str))); // Array ( [0] => Array ( ) )
but how to make $str
to be
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
You should try to use explode
keyword.
$str = '1,2,3,4,5';
print_r(explode(',', $str));
Should print:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Try with:
$str = array(1,2,3,4,5);
Otherwise, if you mean that your input is '1,2,3,4,5' then use explode:
$str = explode(',', '1,2,3,4,5');
In both cases the output of print_r($str); is:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
In addition to @stivlo's answer, you can do this to break a string into an array:
$str = '1,2,3,4,5';
$array = explode(',', $str);
preg_split
is also an option for more complicated splitting situations.
Try explode(',',$str)
.
Or better yet, array_map('intval',explode(',',$str))
if you want integers.
Why not use the explode function?
$arr = explode(",", $str);
Use explode()
to split the string into array, if the $str must be a string. Or declare it as array
.
精彩评论