//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';
$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>";
// 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';
9条答案
按热度按时间d6kp6zgx1#
array_push
和您描述的方法都可以工作。等同于:
erhoui1w2#
最好不要使用
array_push
,只使用你建议的。函数只会增加开销。kzipqqlq3#
根据我的经验,解决方案是罚款(最好的)当钥匙是不重要的:
yshpjwxd4#
你可以使用array_push。它将元素添加到数组的末尾,就像堆栈一样。
你也可以这样做:
koaltpgm5#
yuvru6vn6#
记住,这个方法会覆盖第一个数组,所以只有在你确定的时候才使用!
(see source)
4xrmg8kj7#
q1qsirdb8#
如果您尝试向关联数组追加
vqlkdk9b9#
当一个人想要添加元素时,从零开始的元素索引,我想这也会起作用: