如何将元素添加到php中的空数组?


如果我在PHP中定义一个数组,例如(我没有定义它的大小):

$cart = array();

我是否使用以下方法将元素添加到它?

$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;

不要PHP中的数组有一个add方法,例如cart.add(13)

array_push 和方法你描述的将起作用。

<?php
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
?>

相同

<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);

// Or 
$cart = array();
array_push($cart, 13, 14);
?>

最好不要使用 array_push 只是使用你的建议。这些功能只是增加开销。

//We don't need to define the array, but in many cases it's the best solution.
$cart = array();

//Automatic new integer key higher than the highest 
//existing integer key in the array, starts at 0.
$cart[] = 13;
$cart[] = 'text';

//Numeric key
$cart[4] = $object;

//Text key (assoc)
$cart['key'] = 'test';

未经作者同意,本文严禁转载,违者必究!