PHP
array_push() and array_pop()
Learn to add elements to the end with array_push() and remove from the end with array_pop().
array_push() and array_pop()
The array_push() function adds one or more elements to the end of an array. It changes the array directly and returns the new count. For example, array_push($cart, "Bread") appends "Bread" to the end of $cart.
array_pop() removes the last element and returns it. If the array is empty, it returns null. Together they form a stack: the last item added is the first one removed.
Multiple items and a shortcut
With array_push() you can add several elements at once. array_push($cart, "Bread", "Milk", "Eggs") appends three items and returns the new array length.
For a single item, the bracket form is faster: $cart[] = "Bread"; is a common idiom in PHP. For multiple items, array_push() reads more clearly. No matter which one you pick, the array is updated directly; even if you ignore the return value, the change stays.
Exercise Build a stack and pop from the end
Define a $stack array and start it empty []. Use array_push() to add three values in order: "Alex", "Maya", "Sam". Then use array_pop() to assign the last element to $last and print it with echo $last . "\n".
Show example solution
First add with array_push($stack, "Alex", "Maya", "Sam");. Then remove with $last = array_pop($stack); and print echo $last . "\n";.
Example solution:
<?php
$stack = [];
// Add names, then remove the last and print it
array_push($stack, "Alex", "Maya", "Sam");
$last = array_pop($stack);
echo $last . "\n";
Test yourself
-
What is the output of the code below?
$cart = ["Bread", "Milk"];
$last = array_pop($cart);
echo $last;
Show answer
Milk — Correct. array_pop removes from the end; since the last item is 'Milk', that is printed.
-
Write the function to add to the end
$cart = ["Bread", "Milk"];
____($cart, "Chocolate");
print_r($cart);
Show answer
$cart = ["Bread", "Milk"];
array_push($cart, "Chocolate");
print_r($cart);
-
Match each function to its purpose
- array_push
- Adds to the end
- array_pop
- Removes from the end
- $cart[] = ...
- Adds a single item
-
What is count after array_push?
$cart = ["Bread", "Milk"];
array_push($cart, "Eggs", "Chocolate");
echo count($cart);
Show answer
4 — Correct. There were 2 items, 2 more were added; total is 4.
Next lesson: array_shift() and array_unshift()