PHP array string search Array_search tips _php Tips

Source: Internet
Author: User

PHP Search Array String We typically use Array_search and In_array two functions

array_search() function in_array() to find a key value in the array. If the value is found, the key name of the matching element is returned. Returns False if it is not found.

But Array_search generally uses the first string that matches the requirements in a search array. If the search string contains more than one array, it is not possible to use Array_search. At this point, we use the Array_keys () function to implement a search string that contains more than one array.

Take a look at the following examples:

$array = Array (0 => ' Blue ', 1 => ' Red ', 2 => ' green ', 3 => ' red '); 
$a =array_search ("Blue", $array); The output $a=0; 
$b =array_search (' Red ', $array); will only output $b=1; 
$p = Array_keys ($array, ' red ');//The searched string contains more than 
if (Is_array ($p)) {
  foreach ($p as $v) {echo $val in the array 
    . Appears in the. $v. " ";
   }
} else { 
  echo $val. " Appears in ". Array_search ($val, $array)." ";
}

Case TWO:

$array = Array (4,5,7,8,9,10); 
$found = Array_search (8, $array); Call the Array_search function and output the lookup result 
if ($found) {//If the output key 
echo "is found, the key is". $found; 
} else{//If no output error message is found 
echo "not Found"; 
}

Now let's look at the In_array function

Using In_array (Value,array,type)

Type is optional. If this parameter is set to True, the search data is checked for the same type as the value of the array.

$arr = Array (' Can ', ' how ', ' method ', ' Know ', ' no ', ' no ');
In_array (value,array,type)
$isin = In_array ("How 2", $arr);
if ($isin) {
  echo "in====". $isin;
} else{
  echo "out====". $isin;
}

The above is the entire content of this article, I hope you can enjoy

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.