7

Check if value exists in associative array in PHP

 1 year ago
source link: https://thispointer.com/check-if-value-exists-in-associative-array-in-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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,

Advertisements

<?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";
echo "No, the value does not exists in the associative array";
?>
<?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
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK