For one value, the [] append syntax is concise. array_push() is useful when adding several values in one call and returns the new element count.
$items = ['red', 'green'];
$items[] = 'blue';
array_push($items, 'yellow', 'orange');
print_r($items);Use foreach to display array values; the removed each() function must not be used in current PHP.
array_push($input_array, 'input element');

array_push() we can add elements ( single or a set of elements ) at the end of the array.
$stack = array (1, 2);
array_push ($stack,3,4,5,6); // we are adding four more elements to the array
echo count($stack);
This will display total number of elements inside the array , that is 6 here.
$input=array(0=>'a',1=>'b',2=>'c');
array_push($input,'d','e','f');
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
Output of above code is here
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
5 -> f
Adding 1 to 10 ( or 1 to 100 ) numbers into an array
$input=array();
for($i=1;$i<=10;$i++){
array_push($input,$i);
}
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
0 -> 1
1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> 6
6 -> 7
7 -> 8
8 -> 9
9 -> 10
$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
$output=array_push($input, 'Strawberry');
echo $output; // Output is 5
echo "<br><br>";
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
Output is here.
5
Fruits1 -> Banana
Fruits2 -> Mango
Fruits3 -> Apple
Fruits4 -> Grapes
0 -> Strawberry
Now key of the last element is 0. To add one element with key at the end to an associative array we have to use the code below.
$input=array('Fruits1' =>'Banana','Fruits2'=>'Mango','Fruits3'=>'Apple','Fruits4'=>'Grapes');
$input=$input + array('New_fruit'=>'Strawberry');
foreach ($input as $key => $val) {
echo "$key -> $val
";
}
Output is here
Fruits1 -> Banana
Fruits2 -> Mango
Fruits3 -> Apple
Fruits4 -> Grapes
New_fruit -> Strawberry
$a=array(array("product"=>"apple","quantity"=>2),
array("product"=>"Orange","quantity"=>4),
array("product"=>"Banana","quantity"=>5),
array("product"=>"Mango","quantity"=>7),
);
$b=array("product"=>"Lemon","quantity"=>9);
array_push($a,$b);
//$a[]=$b;
$max=sizeof($a);
for($i=0; $i<$max; $i++) {
foreach ($a[$i] as $key => $val) {
echo "$key -> $val ";
} // inner array while loop
echo "<br>";
} // outer array for loop
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.