Php array string SEARCH array_search tips, array array_search

Source: Internet
Author: User

Php array string SEARCH array_search tips, array array_search

We usually use the array_search and in_array functions to search for Array strings in php.

array_search() Functions andin_array() Look for a key value in the array. If this value is found, the key name of the matching element is returned. If not found, false is returned.

However, array_search generally searches for the first string that meets the requirements in an array. If the search string contains multiple strings in the array, array_search cannot be used. At this time, we use the array_keys () function to implement search strings that contain multiple,

Take a look at the following example:

$ Array = array (0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red '); $ a = array_search ("blue", $ array); // $ a = 0; $ B = array_search ('red', $ array ); // only $ B = 1; $ p = array_keys ($ array, 'red') will be output '); // The search string contains multiple if (is_array ($ p) {foreach ($ p as $ v) {echo $ val. "appears in ". $ v. "" ;}} else {echo $ val. "appears in ". array_search ($ val, $ array ). "";}

Example 2:

$ Array = array (,); $ found = array_search (8, $ array); // call the array_search function and output the search result if ($ found) {// If the output key echo "found, the key is ". $ found;} else {// if no output error message is found, echo "not found ";}

Let's take a look at the in_array function.

In_array (value, array, type)

Type is optional. If this parameter is set to true, check whether the data to be searched is of the same type as the value of the array.

$ Arr = array ('core', 'use', 'method', 'query', 'not', 'not'); // in_array (value, array, type) $ isin = in_array ("How 2", $ arr); if ($ isin) {echo "in = ". $ isin;} else {echo "out = ". $ isin ;}

The above is all the content of this article. I hope you will like it.

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.