Php checks whether a value exists in a multi-dimensional array. Today, we will show you how to judge whether the element value we are looking for exists in the array. here we will introduce in_array for one-dimensional data, but the multidimensional data is a little more complex. Let's take a look at how to judge whether the element value we are looking for exists in the array. here we will introduce how to use in_array for one-dimensional data, but the multidimensional data is a little more complex.
First, let's take a look at in_array to check whether a value exists in the array.
The code is as follows: |
|
$ OS = array ("Mac", "NT", "Irix", "Linux "); Echo "(1 )"; If (in_array ("Irix", $ OS )){ Echo "Got Irix "; } If (in_array ("mac", $ OS) {// in_array () is case sensitive. Echo "Got mac "; } $ A = array ('1', 12.4, 1.13 ); Echo "(2 )"; If (in_array ('12. 4', $ a, true) {// in_array () strict type check Echo "'12. 4' found with strict checkn "; } If (in_array (1.13, $ a, true )){ Echo "1.13 found with strict checkn "; } $ A = array ('P', 'H'), array ('P', 'r'), 'o '); Echo "(3 )"; If (in_array (array ('P', 'H'), $ )){ Echo "'ph' was foundn "; } If (in_array (array ('F', 'I'), $ a) {// in_array () uses arrays as needle Echo "'Fi 'was foundn "; } If (in_array ('O', $ )){ Echo "'O' was foundn "; } ?> The program running result is: (1) Got Irix (2) 1.13 found with strict check (3) 'Ph 'was found' o 'was found |
The above is a one-dimensional array, which is very simple. let's see if there is a value in the multi-dimensional data.
The code is as follows: |
|
$ Arr = array ( Array ('A', 'B '), Array ('C', 'D ') ); In_array ('A', $ arr); // the returned value is always false. Deep_in_array ('A', $ arr); // return true 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 seen in the comments on the in_array method details page of the php help manual. I usually have nothing to do with the help manual, especially the classic comments behind it. it collects the classic methods of many people.
Bytes. Let's first understand...