php's method of determining whether a string exists in an array element

  • 2021-06-29 10:39:00
  • OfStack

Method 1: Use in_array (value, array, type)

type is optional.If this parameter is set to true, check that the data being searched is of the same type as the values of the array.


$arr = array(' Yes? ',' How ',' Method ',' know ',' There are ',' No ');
//in_array(value,array,type)
$isin = in_array(" How 2",$arr);
if($isin){
    echo "in====".$isin;
}else{
    echo "out====".$isin;
}

Method 2:

array_key_exists'array_key_The exists() function determines whether the specified key exists in an array, returns true if it exists, or false if it does not.array_key_exists (key, array)

Method 3:

array_search() function and in_array() 1, look for a key value in the array.If the value is found, the key name of the matching element is returned.If not found, return to false.array_search (value, array, strict), when the data volume is large, use array_key_exists is appropriate, but it takes up a lot of memory.

The array structure is array (1, 2, 3,..) and array (1 = > true, 2 = > false,.., with a memory usage ratio of 1:2.
Specifically related to the internal implementation, the first and second data structures in php are related arrays, similar to each other.

Other additions:

There are three ways to find if an element is in an array, and 1:

in_The array'function searches the array for a given value.in_array (value, array, type) type is optional.If this parameter is set to true, check that the data being searched is of the same type as the values of the array.
array_key_exists'array_key_The exists() function determines whether the specified key exists in an array, returns true if it exists, or false if it does not.

array_key_exists(key,array)

array_search'array_search() function and in_array() 1, look for a key value in the array.If the value is found, the key name of the matching element is returned.If not found, return to false.

array_search(value,array,strict)

From this point of view, when the amount of data is small, such as less than 1000, it will not become a bottleneck to find which one to use.
When there is a large amount of data, use array_key_exists is more appropriate.
Of course array_herekey_exists takes up a large amount of memory, which has been measured
The array structure is array (1, 2, 3,....) and array (1 = > true, 2 = > false, ..)
Their memory usage ratio is 1:2;
This has to do with internal implementations, and in fact the first and second data structures in php are all associated arrays.


Related articles: