English 中文(简体)
如何在PHP中向空数组添加元素?
原标题:
  • 时间:2009-03-24 09:35:00
  •  标签:

If I define an array in PHP such as (I don t define its size):

$cart = array();

Do I simply add elements to it using the following?

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

PHP中的数组没有add方法,例如cart.add(13)吗?

最佳回答

Both array_push and the method you described will work.

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

Based on my experience, solution which is fine(the best) when keys are not important:

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

You can use array_push. It adds the elements to the end of the array, like in a stack.

You could have also done it like this:

$cart = array(13, "foo", $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>";
}

如果您正在尝试将内容添加到关联数组中

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




相关问题
热门标签