Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a php array [closed]

Tags:

arrays

php

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
)
like image 337
fish man Avatar asked Dec 02 '22 01:12

fish man


2 Answers

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
)
like image 73
Patrick Desjardins Avatar answered Dec 25 '22 17:12

Patrick Desjardins


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
)
like image 39
stivlo Avatar answered Dec 25 '22 17:12

stivlo