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';
array_push()
有一个返回值,而其他没有。也许这是其开销的/一个原因?除非您需要该返回值,否则使用其他方法似乎是一种共识。 2) 如果您需要将元素添加到数组的 end,请使用 array_push()
或 +=
连接方法(此答案中未显示),或 $cart[] = 13
方法。使用命名/数字键方法($cart[4] = $object
和 $cart['key'] = 'test'` 方法不保证元素将被添加到end数组,只是它将是 in 数组。
根据我的经验,当键不重要时,解决方案很好(最好):
$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>";
请记住,此方法会覆盖第一个数组,因此请仅在确定时使用!
$arr1 = $arr1 + $arr2;
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"isuru.eshan@gmail.com"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}
当一个人想要使用从零开始的元素索引添加元素时,我想这也会起作用:
// adding elements to an array with zero-based index
$matrix= array();
$matrix[count($matrix)]= 'element 1';
$matrix[count($matrix)]= 'element 2';
...
$matrix[count($matrix)]= 'element N';
$cart[] = 13
方法,不仅因为执行相同操作的字符更少,但它也不会像 array_push() 那样强加函数调用的性能开销。编辑:但是,很好的答案。实际上相同,大多数使用甚至不会注意到性能差异,但有助于了解这些细微差别。$cart[]=...
语法乍一看像是变量赋值而不是隐式 array_push?