Php checks whether a value exists in a multi-dimensional array.

Source: Internet
Author: User
Tags comments manual

First, let's take a look at in_array to check whether a value exists in the array.

The code is as follows: Copy code

<? Php
$ 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: Copy code

$ 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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.