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

问题描述 投票:0回答:9

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

$cart = array();

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

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

PHP中的数组不是有add方法吗,比如

cart.add(13)

php arrays variables
9个回答
1058
投票

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

107
投票

最好不要使用

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

21
投票

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

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

11
投票

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

你也可以这样做:

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

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

4
投票

记住,此方法会覆盖第一个数组,因此仅在确定时才使用!

$arr1 = $arr1 + $arr2;

见来源


2
投票
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
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>";
}

0
投票

如果您尝试追加到关联数组

//append to array   
$countries["continent"] = "Europe";

-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';
© www.soinside.com 2019 - 2024. All rights reserved.