如何在PHP中向空数组添加元素?

时间:2009-03-24 09:35:00

标签: php arrays variables

如果我在PHP中定义一个数组,例如(我没有定义它的大小):

$cart = array();

我是否只需使用以下内容添加元素?

$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;

PHP中的数组是否有add方法,例如cart.add(13)

10 个答案:

答案 0 :(得分:692)

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);
?>

答案 1 :(得分:66)

最好不要使用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';

答案 2 :(得分:10)

根据我的经验,当密钥不重要时,解决方案很好(最好):

Task    task(Map<String,?> args, String name)

Task    task(Map<String,?> args, String name, Closure configureClosure)

Task    task(String name)

Task    task(String name, Closure configureClosure)

答案 3 :(得分:9)

您可以使用array_push。 它将元素添加到数组的末尾,就像在堆栈中一样。

你也可以这样做:

$cart = array(13, "foo", $obj);

答案 4 :(得分:0)

您的首选对我来说很好。

$cart = array();
cart[] = 1:
$cart[]   = 'foo':
$cart = 3;

答案 5 :(得分:0)

$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>";
}

答案 6 :(得分:0)

$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>";

答案 7 :(得分:-1)

当想要添加基于零的元素索引的元素时,我想这也会起作用:

// 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';

答案 8 :(得分:-1)

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>";

答案 9 :(得分:-2)