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,
Frequently Asked:
<?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.