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

How to add elements to an empty array in PHP?

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

1
$cart = array();

我是否只需使用以下方法向它添加元素?

1
2
3
$cart[] = 13;
$cart[] ="foo";
$cart[] = obj;

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


array_push和您描述的方法都有效。

1
2
3
4
5
6
7
8
9
10
11
12
13
$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"[cc lang="php"]";
print_r($cart);
echo"

;< /代码>

相同:

1
2
3
4
5
6
7
8
9
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);

// Or
$cart = array();
array_push($cart, 13, 14);
?>


最好不要使用array_push,只使用你建议的。函数只是增加了开销。

1
2
3
4
5
6
7
8
9
10
11
12
13
//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';


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

1
2
3
4
$cart = [];
$cart[] = 13;
$cart[] ="foo";
$cart[] = obj;

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

你也可以这样做:

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

记住,这个方法覆盖第一个数组,所以只有在确定的时候才使用!

1
$arr1 = $arr1 + $arr2;

(见源代码)


1
2
3
4
5
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo"[cc lang="php"]";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo"

;/或$countries=array();$countries["dk"]=数组("code"=>"dk","name"=>"丹麦","d_code"=>"+45");$countries["dj"]=数组("code"=>"dj","name"=>"djibouti","d_code"=>"+253");$countries["dm"]=数组("code"=>"dm","name"=>"Dominica","d_code"=>"+1");foreach($countries as$country){echo"

1
2
3
";
echo print_r($country);
echo"

号";}< /代码>


你的第一个选择对我来说很好。

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


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

1
2
3
4
5
6
// 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';

它叫做array_push:http://il.php.net/function.array-push