如果我在 PHP 中定义一个数组,例如(我没有定义它的大小):
$cart = array();
我是否只需使用以下内容向其中添加元素?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组不是有add方法,例如cart.add(13)
?
最佳答案
两者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);
?>
关于php - 如何在 PHP 中向空数组添加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/676677/