如果我在PHP中定义一个数组,例如(我没有定义它的大小):
$cart = array();
我只是使用以下内容添加元素吗?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组是否有添加方法,例如,cart.add(13)
?
两者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 ""; print_r($cart); echo "";
是相同的:
最好不要使用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;
你可以使用array_push.它将元素添加到数组的末尾,就像在堆栈中一样.
你也可以这样做:
$cart = array(13, "foo", $obj);