Open In App

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

Last Updated : 02 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

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

$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

$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

Approach 3: Using a Loop

Using a loop to iterate through the array and check if a value exists can be more flexible and provides better control over the search process. This method is especially useful when you want to perform additional operations during the search or handle more complex conditions.

Example:

<?php

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

$value_to_check = 90;
$value_exists = false;

foreach ($student_marks as $subject => $mark) {
    if ($mark == $value_to_check) {
        $value_exists = true;
        break;
    }
}

if ($value_exists) {
    echo "Value exists in the array";
} else {
    echo "Value does not exist in the array";
}

?>

Output
Value exists in the array



Next Article

Similar Reads

three90RightbarBannerImg