Home >Backend Development >PHP Problem >How to loop through an array in php to detect whether it contains a certain value

How to loop through an array in php to detect whether it contains a certain value

青灯夜游
青灯夜游Original
2022-05-26 16:00:111893browse

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.

How to loop through an array in php to detect whether it contains a certain 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;
	}
}
?>

How to loop through an array in php to detect whether it contains a certain value

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 "数组没有指定值";
}
?>

How to loop through an array in php to detect whether it contains a certain value

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn