开发者

how to make a php array [closed]

This question is unlikely to he开发者_JAVA百科lp any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜