Come aggiungere elementi a un array vuoto in PHP?

Se definisco un array in PHP come (non definisco la sua dimensione):

$cart = array();

Posso semplicemente aggiungere elementi ad esso usando il seguente?

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

Gli array in PHP non hanno un metodo add, per esempio, cart.add(13)?

Soluzione

Sia [array_push][1] che il metodo che hai descritto funzionano.


$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc

//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i
Commentari (12)

È meglio non usare array_push e usare solo quello che hai suggerito. Le funzioni aggiungono solo 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';
Commentari (3)

Potete usare array_push. Aggiunge gli elementi alla fine dell'array, come in uno stack.

Avresti anche potuto farlo in questo modo:

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