Home  >  Article  >  Backend Development  >  How to determine whether an element is in a two-dimensional array in php

How to determine whether an element is in a two-dimensional array in php

青灯夜游
青灯夜游Original
2022-07-11 19:47:012135browse

Judgment steps: 1. Use the foreach statement to loop through the outer array elements of the two-dimensional array, with the syntax ""foreach($arr as $v){//loop body code}""; 2. In In the loop body, use "if(is_array($v)){if(array_search(element value,$v)){//Specify the element in the two-dimensional array}}else{if($v===element value) {//The specified element is in the two-dimensional array}}" statement determines whether the specified element is in the two-dimensional array.

How to determine whether an element is in a two-dimensional array in php

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

php determines whether the element is Methods in two-dimensional arrays

Step 1. Use the foreach statement to loop through the outer array elements of the two-dimensional array

foreach($arr as $v){
//循环体代码
}

Traverse Given the $arr array, the value of the current array will be assigned to $v in each loop.

Step 2. In the loop body, determine whether the element is in the two-dimensional array

Use the is_array() function to determine whether the outer element is of array type (whether it is Subarray)

  • If yes, use array_search() to determine whether the specified element is in the subarray

  • If not, use "=== "Just determine whether the current element is the specified element

if(is_array($v)){
	if(array_search(7,$v)){
		echo "指定元素在二维数组中";
		break;
	}
}else{
	if($v===7){
		echo "指定元素在二维数组中";
		break;
	}
}

Complete implementation code:

How to determine whether an element is in a two-dimensional array in php

Improve it:

";
	} else {
		echo "指定元素 $val 不在二维数组中
"; } } $arr = array(1, 2, 3, array(4, 5, 6), 7, 8, array(9, 10)); var_dump($arr); f("h",$arr); f(7,$arr); ?>

How to determine whether an element is in a two-dimensional array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine whether an element is in a two-dimensional array in php. 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