Si defino un array en PHP como (no defino su tamaño):
$cart = array();
¿Simplemente agrego elementos a él usando lo siguiente?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
¿Los arrays en PHP no tienen un método add, por ejemplo, cart.add(13)
?
Tanto array_push
como el método que has descrito funcionarán.
$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>";
Es lo mismo que:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
Es mejor no usar array_push
y sólo usar lo que has sugerido. Las funciones sólo añaden sobrecarga.
//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';
Puedes usar array_push. Añade los elementos al final del array, como en una pila.
También podrías haberlo hecho así:
$cart = array(13, "foo", $obj);