Two judgment methods: 1. Use the end() function and the "===" operator to get the value of the last element of the array, and compare whether the element value is the specified value. The syntax "end( $arr==="specified value ")", if equal, it is, otherwise it is not. 2. Use the array_pop() function and the "===" operator, with the syntax "array_pop($arr==="specified value")". If they are equal, it is yes, and vice versa.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php determines whether the specified value in the array is the last one element, that is, determine whether the last element of the array is the specified value.
You only need to get the last element value, and then determine whether the element value is the specified value.
Method 1: Use the end() function to determine
The end() function can point the pointer inside the array to the last element of the array and return the value of the last element. value, or FALSE if the array is empty.
After obtaining the last element value, use the "===" operator to compare to see whether the two values are equal.
<?php header("Content-type:text/html;charset=utf-8"); function f($arr,$v){ //获取数组中的最后一个元素 $last = end($arr); //判断指定值是否为最后一个元素 if($last===$v){ echo "指定值'$v' 是最后一个数组元素<br>"; }else{ echo "指定值'$v' 不是最后一个数组元素<br>"; } } $arr= array("香蕉"=>"3元","苹果"=>"5元","梨子"=>"6元","橙子"=>"4元","橘子"=>"3元","榴莲"=>"23元"); var_dump($arr); f($arr,2); f($arr,"23元"); ?>
Method 2: Using array_pop() function
array_pop() function will delete the last element in the array and Returns the deleted element.
After obtaining the last element value, use the "===" operator to compare to see whether the two values are equal.
<?php header("Content-type:text/html;charset=utf-8"); function f($arr,$v){ //获取数组中的最后一个元素 $last = array_pop($arr); //判断指定值是否为最后一个元素 if($last===$v){ echo "指定值'$v' 是最后一个数组元素<br>"; }else{ echo "指定值'$v' 不是最后一个数组元素<br>"; } } $arr= array("1","2",3,4,"5","6"); var_dump($arr); f($arr,"2"); f($arr,"6"); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to determine whether the specified value in the array is the last element in php. For more information, please follow other related articles on the PHP Chinese website!