如何在PHP中将元素添加到空数组中?

2022-08-30 05:47:58

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

$cart = array();

我是否只需使用以下方法向其添加元素?

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

PHP 中的数组没有 add 方法,例如 ?cart.add(13)


答案 1

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

$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc

//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
    $cart[] = $i;  
}
echo "<pre>";
print_r($cart);
echo "</pre>";

与以下相同:

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

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

答案 2

最好不要使用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';