Jeśli w PHP zdefiniuję tablicę w taki sposób (nie określam jej rozmiaru):
$cart = array();
Czy po prostu dodaję do niej elementy za pomocą poniższego polecenia?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
Czy tablice w PHP nie mają metody add, na przykład cart.add(13)
?
Zarówno array_push
jak i metoda, którą opisałeś będą działać.
$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>";
Jest taki sam jak:
<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);
// Or
$cart = array();
array_push($cart, 13, 14);
?>
Lepiej jest nie używać array_push
i po prostu użyć tego, co zasugerowałeś. Funkcje tylko dodają koszty ogólne.
//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';
Możesz użyć array_push. To dodaje elementy na koniec tablicy, jak w stosie.
Mógłbyś również zrobić to w ten sposób:
$cart = array(13, "foo", $obj);