When writing a function today, you need to determine whether a string exists in the array, so that we can continue with the subsequent operations. here is a brief introduction. For more information, see
Method 1: Use 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.
The code is as follows:
$ Arr = array ('core', 'use', 'method', 'query', 'no', 'no ');
// In_array (value, array, type)
$ Isin = in_array ("How 2", $ arr );
If ($ isin ){
Echo "in =". $ isin;
} Else {
Echo "out =". $ isin;
}
Method 2:
The array_key_exists 'Array _ key_exists () function checks whether a specified key exists in an array. if the key exists, true is returned. otherwise, false is returned. Array_key_exists (key, array
Method 3:
The array_search () function is the same as the in_array () function. you can find 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. Array_search (value, array, strict): When the data volume is large, it is more appropriate to use array_key_exists, but the occupied memory is relatively large,
The array structure is array (1, 2, 3,...) and array (1 => true, 2 => false,...). the memory usage ratio is.
The specifics are related to internal implementations. in php, the first and second data structures are similar, and they are all associated arrays.
Other supplements:
There are three methods to check whether an element is in an array:
The in_array 'function searches for the given value in the array. 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.
The array_key_exists 'Array _ key_exists () function checks whether a specified key exists in an array. if the key exists, true is returned. otherwise, false is returned.
Array_key_exists (key, array)
The array_search' array _ search () function is the same as the in_array () function. you can find 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.
Array_search (value, array, strict)
From this point of view, when the data volume is small, such as less than 1000, finding which row is used will not become a bottleneck;
When the data volume is large, it is more appropriate to use array_key_exists.
Of course, array_key_exists occupies a large amount of memory.
Array structure: array (1, 2, 3,...) and array (1 => true, 2 => false ,..)
Their memory usage ratio is;
This is related to the internal implementation. In fact, the first and second data structures in php are similar, and they are all associated arrays.