How to add elements to an empty array in PHP?

If I define an array in PHP such as (I don't define its size):

$cart = array();

Do I simply add elements to it using the following?

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

Don't arrays in PHP have an add method, for example, cart.add(13) ?


Both array_push and the method you described will work.

<?php
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
?>

Is the same as:

<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);

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

It's better to not use array_push and just use what you suggested. The functions just add overhead.

//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 = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
链接地址: http://www.djcxy.com/p/58940.html

上一篇: PHP将一个数组附加到另​​一个(而不是数组)

下一篇: 如何将元素添加到PHP中的空数组?