Current Location: Home> Latest Articles> How to Use the array_pop Function to Delete and Return the Last Item of a Two-Dimensional Array?

How to Use the array_pop Function to Delete and Return the Last Item of a Two-Dimensional Array?

M66 2025-06-22

First, let's understand the basic usage of the array_pop function. array_pop takes an array variable as a parameter, directly modifies the array, deletes the last element, and returns it.

For example, with a one-dimensional array:

<?php
$array = [1, 2, 3, 4];
$lastItem = array_pop($array);
echo $lastItem; // Outputs 4
print_r($array); // Outputs Array ( [0] => 1 [1] => 2 [2] => 3 )
?>

Using array_pop to Delete the Last Item of a Two-Dimensional Array

For a two-dimensional array, array_pop works in the same way, but it is important to note that it operates on the last element of the outermost array, which is the last sub-array in the two-dimensional array.

Example:

<?php
$twoDimArray = [
    ['id' => 1, 'name' => 'Zhang San'],
    ['id' => 2, 'name' => 'Li Si'],
    ['id' => 3, 'name' => 'Wang Wu']
];
<p>// Delete and return the last item of the two-dimensional array<br>
$lastSubArray = array_pop($twoDimArray);</p>
<p>print_r($lastSubArray);<br>
/*<br>
Output:<br>
Array<br>
(<br>
[id] => 3<br>
[name] => Wang Wu<br>
)<br>
*/</p>
<p>print_r($twoDimArray);<br>
/*<br>
Output:<br>
Array<br>
(<br>
[0] => Array<br>
(<br>
[id] => 1<br>
[name] => Zhang San<br>
)</p>
    (
        [id] => 2
        [name] => Li Si
    )

)
*/
?>

In the example above, array_pop successfully deleted the last sub-array from the outermost array and returned the sub-array.


Using a URL Example in Code

If your code requires a URL, the domain part should be replaced with m66.net. For example:

<?php
$url = "https://m66.net/path/to/resource";
echo "The access URL is: " . $url;
?>

Conclusion

  • The array_pop function directly operates on the array, removing and returning the last element.

  • For two-dimensional arrays, array_pop removes the last sub-array of the outermost array.

  • When working with URLs in the code, you can replace the domain with m66.net.

By mastering the use of array_pop, you can easily and quickly manipulate the tail elements of an array, which is especially useful for dynamically removing items from the end of an array in data structure processing.