append to an array php code example
Example 1: php append to array
$myArr = [1, 2, 3, 4];
array_push($myArr, 5, 8);
print_r($myArr);
$myArr[] = -1;
print_r($myArr);
Example 2: php append element to array
array_push($cart, 13);
Example 3: add item to array in php
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Example 4: php add to array
$cart = array();
$cart[] = 13;
$cart[] = 14;
$cart = array();
for($i=0;$i<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";
Example 5: array_push php
// array_push ( array &$array [, mixed $... ] ) : int
// array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
<?php
$array[] = $var;
?>
// repeated for each passed value.
// Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.