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
<?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

Similar Reads

Using in_array() Function

The in_array() function checks if a value exists in an array. It returns true if the value is found, and false otherwise....

Using array_search() Function

The array_search() function searches for a value in an array and returns the key if found. If the value is not found, it returns false....

Using array_key_exists() Function

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....

Using a Loop

If you need to perform a more complex search, you can use a loop to iterate through the array and check each element. The loop iterates through the array and compares each element with the search value 30. If a match is found, it prints the index and breaks the loop....