Home >Backend Development >PHP Problem >How to loop through an array in php to detect whether it contains a certain value
Detection method: 1. Use the foreach statement to loop through the array, with the syntax "foreach ($array as $value){}"; 2. In the loop body, use the "$value===specified value" statement Determine whether the array contains the specified value (that is, whether the current array element is equal to the specified value). If equal, the array contains the value, otherwise it does not contain the value.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php loop array detection Method to determine whether a certain value is included
1. Use the foreach statement to loop through the array
foreach ($array as $value){ 语句块; }
Traverse the given $ array Array, assign the value of the current array to $value in each loop.
2. In the loop body, use the === operator to detect whether a certain value is included
$value===指定值
In each loop, determine Whether the current array value $value is equal to the specified value:
If it is equal, the array contains the value
If it is not equal, the array does not contain it The value
Note: === is strictly equal, the values and types of the two operands must be consistent before they are judged to be equal
, The string "1" and the value 1 are different.
Implementation code:
<?php header("Content-type:text/html;charset=utf-8"); $arr= array("2",1,"3",4,2,3); var_dump($arr); foreach($arr as $value){ if($value===1){ echo "包含指定值"; break; } } ?>
I will improve it:
<?php header("Content-type:text/html;charset=utf-8"); $arr= array("2",1,"3",4,2,3); var_dump($arr); $f=false; foreach($arr as $value){ if($value==="1"){ $f=TRUE; break; } } if($f){ echo "数组有指定值"; }else{ echo "数组没有指定值"; } ?>
Recommended learning: "PHP video tutorial"
The above is the detailed content of How to loop through an array in php to detect whether it contains a certain value. For more information, please follow other related articles on the PHP Chinese website!