In PHP, we often process JSON data. After converting a JSON string to a PHP array through the json_decode() function, we may need to get the last element of the array. The end() function is a very convenient method, which can help us achieve this requirement.
In this article, we will explain how to use the end() function to get the last value of the JSON decoded array and provide a sample code.
The end() function is used to move the "pointer" inside the array to the last element and return the value of that element. It does not change the structure of the array, it simply obtains the last element through an internal pointer. Therefore, end() is a very concise and efficient way to get the last element of an array.
First, we need to decode a JSON string into a PHP array. Then, use the end() function to get the last element of the array. Here is a complete example code:
<?php
// JSON String
$jsonString = '{"name": "John", "age": 30, "city": "New York"}';
// Will JSON String解码为 PHP Array
$data = json_decode($jsonString, true);
// 获取Array的最后一个值
$lastValue = end($data);
// Output the last value
echo "The last value is: " . $lastValue;
?>
In this example, we first convert a JSON string into an associative array. Then, we use the end() function to get the last element of the array. Since the end() function returns the value in the array, not the key, the final output will be "New York" , that is, the value corresponding to city in the array.
In practical applications, you may encounter situations where the JSON data contains URLs. If we need to modify the domain name in the JSON data and replace it with the specified domain name (for example, m66.net ), we can traverse and replace the array after decoding. Here is a more complex example showing how to handle JSON data containing URLs: