如何制作一个php数组

fis*_*man 4 php arrays

我试过转移$str成阵列组.

$str = '1,2,3,4,5';
print_r(array($str)); //this get  Array ( [0] => 1,2,3,4,5 )
Run Code Online (Sandbox Code Playgroud)

我试过了 compact

print_r(array(compact($str))); // Array ( [0] => Array ( ) )
Run Code Online (Sandbox Code Playgroud)

但如何$str成为

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Run Code Online (Sandbox Code Playgroud)

Pat*_*ins 8

您应该尝试使用explode关键字.

$str = '1,2,3,4,5';
print_r(explode(',', $str));
Run Code Online (Sandbox Code Playgroud)

应打印:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Run Code Online (Sandbox Code Playgroud)


sti*_*vlo 6

试试:

$str = array(1,2,3,4,5);
Run Code Online (Sandbox Code Playgroud)

否则,如果您的意思是输入为"1,2,3,4,5",那么请使用explode:

$str = explode(',', '1,2,3,4,5');
Run Code Online (Sandbox Code Playgroud)

在两种情况下print_r的输出($ str); 是:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Run Code Online (Sandbox Code Playgroud)