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

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

$cart = array();

我只是简单地添加元素到它使用下面?

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

PHP中的数组不是有一个add方法吗,例如cart.add(13)?

1372561 次浏览

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

你也可以这样做:

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

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

当一个人想要添加以零为基础的元素索引时,我想这也可以工作:

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

记住,这个方法会覆盖第一个数组,所以只在确定的情况下使用!

$arr1 = $arr1 + $arr2;

(# EYZ0)

根据我的经验,当关键字不重要时,哪种解决方案是最好的:

$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
$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>";
}
$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>";