How to make a php array

I tried passing $str as a group of arrays.

 $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

 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 
+4
source share
6 answers

Try:

 $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 is print_r ($ str); :

 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 
+6
source

You must use the explode keyword.

 $str = '1,2,3,4,5'; print_r(explode(',', $str)); 

Must print:

 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) 
+8
source

In addition to @stivlo's answer, you can do this to split a string into an array:

 $str = '1,2,3,4,5'; $array = explode(',', $str); 

preg_split also an option for more complex split situations.

+1
source

Try explode(',',$str) .

Or better yet, array_map('intval',explode(',',$str)) if you need integers.

+1
source

Why not use the explode function?

 $arr = explode(",", $str); 
+1
source

Use explode() to split a string into an array if $ str should be a string. Or declare it as an array .

+1
source

All Articles