Home > Article > Backend Development > PHP array learning: Obtaining the first/last element (1)
In the previous article, we introduced how PHP calculates the length of an array. We know how the count() function counts the number of two-dimensional (multi-dimensional) array elements. If you need it, you can check out "PHP Array Learning to calculate the length of a two-dimensional array using a two-dimensional array》. In this article, we continue to study the array series!
This article will introduce to you how to get the first element or the last element of a PHP array: array_shift() and array_pop(). Let’s take a look at these two functions through code examples. How do they get the first array element and the last array element.
array_shift() function gets the first element in the array
##Let’s take a look at the following example:<?php header("Content-type:text/html;charset=utf-8"); $arr= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump($arr); //获取数组中的第一个元素 $first = array_shift($arr); echo "数组的第一个元素为:".$first; ?>Output result:
The array_shift() function can delete the first element in the array and then return the first deleted array element; if the array is empty, NULL will be returned.
array_pop() function gets the last element in the array
Let’s look at an example first:<?php header("Content-type:text/html;charset=utf-8"); $arr= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump($arr); //获取数组中的第一个元素 $first = array_pop($arr); echo "数组的最后一个元素为:".$first; ?>Output result:
##array_pop() is similar to the array_shift() function. It can not only "get the last element in the array", but also can be applied In the operation of "removing the element at the end of the array".
Use the var_dump() function after the array_pop() function to output the array, and you will find that the original last array element no longer exists:
The array_pop() function can delete the last element in the array and then return the last deleted array element; and if the array is empty, NULL will be returned.
Summary: array_shift() and array_pop() functions actually remove the first element or the last element from the array element, and then returns the removed element; at this time, the element no longer exists in the array.
Okay, that’s all. If you want to know anything else, you can click this. → →
php video tutorialFinally, I would like to recommend a free video tutorial on PHP arrays:
PHP function array array function video explanationThe above is the detailed content of PHP array learning: Obtaining the first/last element (1). For more information, please follow other related articles on the PHP Chinese website!