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

luaexgnf  于 2023-04-04  发布在  PHP
关注(0)|答案(9)|浏览(837)

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

$cart = array();

我是否简单地使用以下方法向它添加元素?

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

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

d6kp6zgx

d6kp6zgx1#

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

erhoui1w2#

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

kzipqqlq3#

根据我的经验,解决方案是罚款(最好的)当钥匙是不重要的:

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

yshpjwxd4#

你可以使用array_push。它将元素添加到数组的末尾,就像堆栈一样。
你也可以这样做:

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

koaltpgm5#

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

yuvru6vn6#

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

$arr1 = $arr1 + $arr2;

see source

4xrmg8kj

4xrmg8kj7#

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

q1qsirdb8#

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

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

vqlkdk9b9#

当一个人想要添加元素时,从零开始的元素索引,我想这也会起作用:

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

相关问题