How to Check if a Value Exists in an Associative Array in PHP?

Given an Associative array, the task is to check whether a value exists in the associative array or not. There are two methods to check if a value exists in an associative array, these are – using in_array(), and array_search() functions. Let’s explore each method with detailed explanations and code examples.

Table of Content

  • Using in_array() Function
  • Using array_search() Function

Approach 1: Using in_array() Function

The in_array() function checks if a value exists in an array. However, this function is not suitable for associative arrays, as it only works for indexed arrays.

PHP
<?php

$student_marks = array(
    "Maths" => 95, 
    "Physics" => 90,   
    "Chemistry" => 96, 
    "English" => 93,   
    "Computer" => 98
);

// Check a value exists in the array
if (in_array(90, $student_marks)) {
    echo "Value exists in the array";
} else {
    echo "Value does not exist in the array";
}

?>

Output
Value exists in the array

Approach 2: Using array_search() Function

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

PHP
<?php

$student_marks = array(
    "Maths" => 95, 
    "Physics" => 90,   
    "Chemistry" => 96, 
    "English" => 93,   
    "Computer" => 98
);

// Check a value exists in the array
$key = array_search(90, $student_marks);

if ($key !== false) {
    echo "Value exists in the array";
} else {
    echo "Value does not exist in the array";
}

?>

Output
Value exists in the array

Contact Us