【发布时间】:2010-10-15 04:04:21
【问题描述】:
如果我在 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)?
【问题讨论】:
array_push 和你描述的方法都可以。
$customArray = array();
$customArray[] = 20;
$customArray[] = 21;
以上是正确的,但以下是为了进一步理解
$customArray = array();
for($i=0;$i<=12;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($customArray);
echo "</pre>";
【讨论】:
根据我的经验,当键不重要时,最好的解决方案:
$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>";
【讨论】:
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);
?>
【讨论】:
$cart[] = 13 方法,不仅因为执行相同操作的字符更少,但也不会像 array_push() 那样强加函数调用的性能开销。编辑:但是,很好的答案。实际上相同,大多数使用甚至不会注意到性能差异,但有助于了解这些细微差别。
$cart[]=... 语法乍一看像是变量赋值而不是隐式array_push?
$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>";
}
【讨论】:
【讨论】:
最好不要使用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 数组。
当一个人想要使用从零开始的元素索引添加元素时,我想这也可以:
// 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';
【讨论】:
【讨论】: