如果我在PHP中定义一个数组,如(我没有定义它的大小):
$cart = array();
我只是简单地添加元素到它使用下面?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组不是有一个add方法吗,比如cart.add(13)?
如果我在PHP中定义一个数组,如(我没有定义它的大小):
$cart = array();
我只是简单地添加元素到它使用下面?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组不是有一个add方法吗,比如cart.add(13)?
当前回答
$cart = array();
$cart[] = 11;
$cart[] = 15;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i = 0; $i <= 5; $i++){
$cart[] = $i;
//if you write $cart = [$i]; you will only take last $i value as first element in array.
}
echo "<pre>";
print_r($cart);
echo "</pre>";
其他回答
你可以使用array_push。 它将元素添加到数组的末尾,就像在堆栈中一样。
你也可以这样做:
$cart = array(13, "foo", $obj);
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);
?>
最好不要使用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';
根据我的经验,当关键字不重要时,哪种解决方案是最好的:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
$cart = array();
$cart[] = 11;
$cart[] = 15;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i = 0; $i <= 5; $i++){
$cart[] = $i;
//if you write $cart = [$i]; you will only take last $i value as first element in array.
}
echo "<pre>";
print_r($cart);
echo "</pre>";