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)
?
Sia array_push
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<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";
È lo stesso di:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
È 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';
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);