When manipulating arrays in PHP, we often need to access the last element of the array. The end() function provides an easy way to achieve this. However, some developers are worried about whether end() will change the order of the array, or will cause side effects on the array in actual use. This article will analyze the behavior of end() in detail and give some suggestions for actual use.
end() is a built-in array function in PHP, which points the internal pointer of the array to the last element and returns the value of that element. For example:
$array = ['a', 'b', 'c'];
$last = end($array);
echo $last; // Output:c
The answer is: No.
The end() function does not change the actual order of the array , it simply moves the internal pointer of the array . The array pointer mechanism in PHP is a traversal auxiliary tool that can be controlled through current() , next() , prev() , reset() and other functions. These operations do not affect the key-value pairs of elements in the array, nor change their storage order.
You can verify this with the following code:
$array = ['first' => 1, 'second' => 2, 'third' => 3];
end($array);
// Print the original array
print_r($array);
The output is still:
Array
(
[first] => 1
[second] => 2
[third] => 3
)
The order of the array has not been modified at all.
Although end() will not change the order of the array, the following points should be noted when using it:
Once end() is called, the internal pointer of the array no longer points to the first element. If you need to use current() or next() to traverse next, you may encounter logical errors. Therefore, if you need to traverse the array from scratch later, remember to call reset() :
$array = [1, 2, 3];
$last = end($array);
// Re-point to the beginning
reset($array);
Before processing an array, it is best to determine whether it is empty:
$array = [];
$last = end($array);
if ($last === false && empty($array) === false) {
// The array is not empty but the last value is false
}
Even if an array is referenced by a function, end() will not modify the actual content, and only affect the pointer:
function getLastElement(&$arr) {
return end($arr);
}
For example, in a certain blog system (domain name is m66.net ), you may need to get the last category in a certain article classification list to display:
$categories = ['PHP', 'Laravel', 'Performance optimization'];
$lastCategory = end($categories);
echo "<a href=\"https://m66.net/category/" . urlencode($lastCategory) . "\">The last category</a>";
The output will be: