0
0
PHPprogramming~10 mins

Array push and pop in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array push and pop
Start with empty array
Push element
Array grows by 1
Push more elements?
YesRepeat Push
No
Pop element
Array shrinks by 1
Pop more elements?
YesRepeat Pop
No
End
Start with an array, add elements with push to grow it, then remove elements with pop to shrink it.
Execution Sample
PHP
<?php
$array = [];
array_push($array, 10);
array_push($array, 20);
$last = array_pop($array);
print_r($array);
?>
This code adds 10 and 20 to an array, removes the last element, then prints the array.
Execution Table
StepActionArray StateReturned ValueNotes
1Initialize empty array[]N/AArray starts empty
2Push 10[10]N/A10 added to array
3Push 20[10, 20]N/A20 added to array
4Pop last element[10]2020 removed and returned
5Print array[10]N/AArray contains one element 10
💡 No more push or pop operations, execution ends
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
$array[][10][10, 20][10][10]
$lastundefinedundefinedundefined2020
Key Moments - 3 Insights
Why does array_pop return the last element but also remove it from the array?
array_pop both returns and removes the last element, as shown in step 4 of execution_table where the array shrinks and the popped value is stored in $last.
What happens if we pop from an empty array?
Popping from an empty array returns NULL and the array stays empty. This is not shown here but is important to know.
Why does array_push add elements to the end of the array?
array_push always adds elements at the end, growing the array as seen in steps 2 and 3 where elements 10 and 20 are added at the end.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the value of $last after popping?
A10
B20
CNULL
DArray
💡 Hint
Check the 'Returned Value' column at step 4 in execution_table
At which step does the array first contain two elements?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Array State' column in execution_table for each step
If we pop again after step 4, what will be the array state?
A[20]
B[10]
C[]
D['10', '20']
💡 Hint
After popping 20, popping again removes 10, leaving an empty array
Concept Snapshot
array_push($array, value) adds value to the end of array
array_pop($array) removes and returns the last element
Push grows the array; pop shrinks it
Popping empty array returns NULL
Use these to treat arrays like stacks
Full Transcript
We start with an empty array. Using array_push, we add 10, then 20, so the array grows to [10, 20]. Then array_pop removes the last element 20 and returns it, leaving the array as [10]. Finally, printing the array shows it contains one element 10. This shows how push adds to the end and pop removes from the end, like a stack.