Check if value exists in associative array in PHP

This tutorial will discuss about a unique way to check if value exists in associative array in php.

Fetch all values fields, from all the key-value pairs of an associative array using the array_values() method. It accepts an associative array as argument, and returns an array containing all the values from this associative array. ?

Once we have the array of values only, then we can use the in_array() to check if it contains the given value or not.

In the below example, we have an associative array containing ranking and names as key-value pairs. We will check if it contains a value “Smriti” or not.

Let’s see the complete example,

<?php
$name = 'Smriti';

$arr = array(
        'first' => 'Ritika',
        'second' => 'Shaunak',
        'third' => 'Atharv',
        'fourth' => 'Smriti');

// "array_values($arr)" gives all the values from associative array
// use "in_array()" to check if this new array contains a value
if (in_array($name, array_values($arr)))
{
    echo "Yes, the value exists in the associative array";
}
else
{
    echo "No, the value does not exists in the associative array";
}
?>

Output

Yes, the value exists in the associative array

Summary

We learned how to check if an associative array contains a value or not in PHP. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top