How to use array_key_exists() Function In PHP
If you want to search for a key in an associative array, array_key_exists() is the right function to use. It checks if the given key or index exists in the array. The array_key_exists() function checks if the key “C” exists in the associative array.
Example: This example shows the use of array-key_exists() function for searching an item in an array.
<?php
$arr = array(
'A' => 10,
'B' => 20,
'C' => 30,
'D' => 40,
'E' => 50
);
$itemKey = 'C';
if (array_key_exists($itemKey, $arr)) {
echo "$itemKey exist in array.";
} else {
echo "$itemKey not exist in array.";
}
?>
Output
C exist in array.
Search an Item in an Array in PHP
Given an array and an item, the task is to search whether the given item is present in the array or not.
Below are the approaches to search an item in an array in PHP:
Table of Content
- Using in_array() Function
- Using array_search() Function
- Using array_key_exists() Function
- Using a Loop