In PHP interview questions, basic operating knowledge points about PHP arrays often appear, such as PHP to delete duplicate elements in arrays. Element,php array transfer Change to the string and other basic questions.
This article will introduce to you a common interview question about PHP arrays. PHP gets the last element of the array Element's key and value method.
Below we combine code examples to introduce in detail how PHP obtains the key and value of the last element of an array.
In PHP, there is a function that can directly get the value of the last element in the array.
end() function: Moves the internal pointer of array to the last cell and returns its value.
The code example is as follows:
<?php $arr = ['1' => 'name', '3' => 2, 5 => 6, 'name' => '张三']; $a = end($arr); echo $a;
Access through the browser, and the result is as follows:
As shown in the picture Indicates that we directly use the end function to get the value of the last element of the array.
Then we can use a simple method to get the subscript of the last element, which is the key name.
The code example is as follows:
<?php /** * PHP获取数组中最后一个元素下标和值 */ $arr = ['1' => 'name', '3' => 2, 5 => 6, 'name' => '张三']; $a = end($arr); echo $a; echo "<br>"; foreach ($arr as $k => $v) { if ($v === $a) { echo $k; } }
Here we mainly use the foreach loop to traverse the array key values, and then use the if statement to traverse the array value and end The values obtained by the function are compared. If they are completely equal, the corresponding subscript can be output, which is the key name of the last element.
The final result is as shown below:
This question is about PHP getting the key and value of the last element in the array Specific method introduction , very simple and easy to understand. Hope it helps those in need!
If you want to know more about PHP, you can follow PHP Chinese website PHP video tutorial, welcome Please refer to and learn from everyone!
The above is the detailed content of How to get the key and value of the last element of an array in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!