Consider the following PHP code:
$fruits = ['apple', 'banana'];
array_push($fruits, 'cherry');
$popped = array_pop($fruits);
echo $popped . ', ' . implode(', ', $fruits);What will be printed?
$fruits = ['apple', 'banana']; array_push($fruits, 'cherry'); $popped = array_pop($fruits); echo $popped . ', ' . implode(', ', $fruits);
Remember that array_pop removes the last element and returns it.
The array_push adds 'cherry' to the end of the array. Then array_pop removes and returns 'cherry'. So $popped is 'cherry', and the remaining array is ['apple', 'banana'].
Given this PHP code:
$numbers = [1, 2, 3]; array_push($numbers, 4); array_pop($numbers); array_push($numbers, 5); array_pop($numbers); array_push($numbers, 6); print_r($numbers);
What will print_r output?
$numbers = [1, 2, 3]; array_push($numbers, 4); array_pop($numbers); array_push($numbers, 5); array_pop($numbers); array_push($numbers, 6); print_r($numbers);
Each array_pop removes the last element added.
After pushing 4, array is [1,2,3,4]. Pop removes 4. Push 5, array is [1,2,3,5]. Pop removes 5. Push 6, array is [1,2,3,6].
Look at this PHP code:
$colors = ['red'];
array_push($colors, 'green', 'blue');
$popped = array_pop($colors);
echo $popped . ', ' . implode(', ', $colors);What will be printed?
$colors = ['red']; array_push($colors, 'green', 'blue'); $popped = array_pop($colors); echo $popped . ', ' . implode(', ', $colors);
array_push can add multiple elements at once. array_pop removes the last element.
After pushing 'green' and 'blue', array is ['red', 'green', 'blue']. array_pop removes 'blue'. So $popped is 'blue', and array is ['red', 'green'].
Analyze this PHP code:
$items = []; $popped = array_pop($items); echo $popped === null ? 'null' : $popped;
What will be printed?
$items = []; $popped = array_pop($items); echo $popped === null ? 'null' : $popped;
What happens when you pop from an empty array?
array_pop returns null if the array is empty. No error is raised.
Consider this PHP code snippet:
$stack = []; array_push($stack, 'a'); array_push($stack, 'b', 'c'); array_pop($stack); array_push($stack, 'd'); array_pop($stack); array_pop($stack);
How many elements remain in $stack after all operations?
Count carefully each push and pop step.
Step by step:
Start: []
Push 'a': ['a']
Push 'b', 'c': ['a','b','c']
Pop removes 'c': ['a','b']
Push 'd': ['a','b','d']
Pop removes 'd': ['a','b']
Pop removes 'b': ['a']
So 1 element remains.