Using PHP array_pop to Remove and Return the Last Element of an Array
This article explains how PHP's array_pop function removes and returns the last element of an array, demonstrates its syntax, provides a complete code example with expected output, and highlights its usefulness for array manipulation in backend development.
In PHP we often need to handle array data. Sometimes we need to take the last element from an array and operate on it. PHP provides a very convenient function for this purpose: the "array_pop" function.
The "array_pop" function is used to pop and return the last element of an array. Its syntax is as follows:
mixed array_pop ( array &$array )The function accepts an array as a parameter, removes the last element from the array, and returns that element. If the array is empty, it returns null.
Next, let's look at a code example that uses the "array_pop" function:
<?php
// Define an array
$fruits = array("apple", "banana", "orange", "grape");
// Use array_pop to pop and return the last element
$last_fruit = array_pop($fruits);
// Output the popped element
echo "Popped element is: " . $last_fruit . "\n";
// Output the remaining array
echo "Remaining array is: \n";
print_r($fruits);
?>The above code defines an array named "fruits" containing several fruit names. It then uses "array_pop" to pop the last element, assigns it to the variable "$last_fruit", and echoes it. Afterwards, it uses "print_r" to display the remaining array.
If you run the code, you will get the following output:
Popped element is: grape
Remaining array is:
Array
(
[0] => apple
[1] => banana
[2] => orange
)As shown, the "array_pop" function removed the last element "grape" from the array and returned it. The remaining array contains only the other fruit names.
Summary
By using PHP's "array_pop" function, we can easily pop and return the last element of an array. This function is very useful for handling array data. Hope this article helps you!
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.