Home > Article > Backend Development > PHP determines whether a certain value exists in a multidimensional array_PHP tutorial
Today we will introduce to you how to determine whether the element value we are looking for exists in the array. Here, if it is one-dimensional data, you can directly in_array, but multi-dimensional data is a bit more complicated.
Let’s first solve the problem of in_array checking whether a certain value exists in the array
The code is as follows
|
Copy code
|
||||
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) { echo "Got Irix"; } if (in_array("mac", $os)) {//in_array() is case sensitive
echo "Got mac"; |
The code is as follows | Copy code |
$arr = array( array('a', 'b'), array('c', 'd') ); in_array('a', $arr); // The return value at this time is always false deep_in_array('a', $arr); // Returns true value at this time function deep_in_array($value, $array) { foreach($array as $item) { If(!is_array($item)) { If ($item == $value) { return true; } else { Continue; } If(in_array($value, $item)) { return true; } else if(deep_in_array($value, $item)) { return true; } } Return false; } This method is found in the comments under the in_array method detailed explanation page of the PHP help manual. If you have nothing to do, read the help manual more often, especially the classic comments at the end, which collects many people's classic methods. |