如果我在PHP中定义了一个数组,例如(我没有定义它的大小):
$cart = array();
我是否只需要使用以下方式将元素添加到它中?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组没有add方法,比如说,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 "<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()
有一个返回值,而其他方法没有。也许这是它的开销较大的原因之一?除非你需要那个返回值,否则似乎达成了使用其他方法的共识。array_push()
或连接的+=
方法(本答案未显示),或者$cart[] = 13
方法。使用命名/数字键方法($cart[4] = $object
和$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>";
$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>";
}
如果你想要追加一个关联数组
//append to array
$countries["continent"] = "Europe";
当需要使用从零开始的元素索引添加元素时,我想这也可以起作用:
// 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()
则会带来性能开销。编辑:但是,非常好的答案。实际上是相同的,大多数情况下甚至不会注意到性能差异,但知道这些微妙之处还是有帮助的。 - Mattygabe$cart[]=...
这个语法看起来更像变量赋值而不是隐式的数组添加?请帮我翻译。 - Brad Hein