In this tutorial, you are going to learn the use of in_array() and array_key_exists() functions in php.
The function in_array() is used to determine whether a value exists in an array or not.
Whereas function array_key_exists() is used to determine whether a given key or index exists in the array or not.
We have described below both the function in detail.
IN_ARRAY() FUNCTION
Syntax: in_array($value, $arr, $type);
Three types of parameters are used in this function which are described below.
- $value- This parameter represents the value to be searched.
- $arr- It represents the array for which the existence of the value is checked.
- $type- This is a boolean parameter which can be set to either TRUE or FALSE.
Result/ Return Value: The successful execution of the script will return TRUE i.e if the array contains the value. Else, it will return FALSE.
Example: An example of in_array() function is shown below.
Output: The following output will be generated after running the above Php script.
Here, we have checked whether element ‘w3training’ exists in the array ‘$a’ or not. Clearly, the output is showing ‘Match Found’ which means the element or the value ‘w3training’ exists in the array ‘$a”.
ARRAY_KEY_EXISTS() FUNCTION
Syntax: array_key_exists($key, $arr);
Two types of parameters are used in this function which is described below.
- $key- This mixed parameter represents the key(value) to be checked.
- $arr- This parameter represents the array for which the existence of the key is checked.
Result/ Return Value: On the successful execution of the Php script, TRUE will be returned. And if the program fails, FALSE will be returned.
Example: An example of array_key_exists() function is shown below. Output: You will get the following output after the successful execution of the above Php codes.
Here, we have checked whether the key ‘Maruti’ exists in the array ‘$a’ or not. Clearly, the output is showing Key exists! that means, the key Maruti is present in the array $a. To print the possible outcomes we have used if else statement.
We have tried to provide you the best possible information about the use of in_array() and array_key_exists() functions in php. Hope you liked this article. For further updates and related information, stay connected to our php blogs.