Home > Article > Backend Development > How to determine whether an element is in a two-dimensional array in php
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.
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:
Improve it:
<?php header("content-type:text/html;charset=utf-8"); function f($val,$arr) { $con = 0; foreach ($arr as $v) { if (is_array($v)) { if (array_search($val, $v)) { $con = 1; break; } } else { if ($v === $val) { $con = 1; break; } } } if ($con == 1) { echo "指定元素 $val 在二维数组中<br>"; } else { echo "指定元素 $val 不在二维数组中<br>"; } } $arr = array(1, 2, 3, array(4, 5, 6), 7, 8, array(9, 10)); var_dump($arr); f("h",$arr); f(7,$arr); ?>
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!