Home > Article > Backend Development > Is it possible to perform array search in php?
Array search can be performed in php. PHP provides two array search functions: 1. array_search(), which can search for a given value in the array and return the corresponding key name. The syntax "array_search (search value, array, whether to compare types when searching)" returns The value is of string type; 2. array_keys(), used to search for a given value in the array and return the corresponding key name. The syntax is "array_keys (array, search value, comparison type)", and the return value is an array type.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
Array search can be performed in php.
There are two array search functions provided in php:
array_search()
array_keys()
Both functions can search for a given value in an array and return the corresponding key name (subscript). The difference is: the return value of array_search() is of string type, while the return value of array_keys() is of array type.
1. Use array_search() for array search
array_search() function searches for a key value in the array and returns the corresponding key name.
array_search(value,array,strict)
Parameters | Description |
---|---|
value | Required . Specifies the key value to search for in the array. |
array | Required. Specifies the array to be searched. |
strict | Optional. If this parameter is set to TRUE, the function searches the array for elements of the same data type and value. Possible values:
|
Example: Search for the key value "red" in the array and return its key name
<?php header("Content-type:text/html;charset=utf-8"); $a=array("a"=>"red","b"=>"green","c"=>"blue"); var_dump($a); echo array_search("red",$a); ?>
2. Use array_keys() for array search
array_key() function can obtain some or all key names in the array.
array_keys(array,value,strict)
Array search can only be performed when the value parameter is set,
Parameter | Description |
---|---|
array | Required. Specifies an array. |
value | Optional. You can specify a key value, and then only the key name corresponding to that key value will be returned. |
strict | Optional. Used with the value parameter. Possible values:
|
Example: Search for the key value "Highlander" in the array and return its key name
<?php header("Content-type:text/html;charset=utf-8"); $a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander"); var_dump($a); var_dump(array_keys($a,"Highlander")); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Is it possible to perform array search in php?. For more information, please follow other related articles on the PHP Chinese website!