How to use the array_search function In PHP
The array_search function is used to search for a given value in an array and return the corresponding key if the value is found. If the value is not found, it returns false.
Syntax:
bool = array_search($search_value, $array);
<?php
$array = array('name' => 'geek', 'age' => '22');
if (array_search('geek', $array) !== false) {
echo 'Found the key';
} else {
echo 'Key not found';
}
?>
Output
Found the key
How to check a key exists in an array in PHP ?
We have given an array arr and a Key key, the task is to check if a key exists in an array or not in PHP.
Examples:
Input : arr = ["Geek1", "Geek2", "1", "2","3"]
key = "2"
Output : Found the Key
Input : arr = ["Geek1", "Geek2", "1", "2","3"]
key = 9
Output : Key not Found
The problem can be solved using PHP inbuilt function for checking key exists in a given array. The in-built function used for the given problem are:
Table of Content
- Using array_key_exists() Method:
- Using isset() Method:
- Using the array_search function:
- Using array_keys