Skip to content
Advertisement

PHP – Check if value exists in array but only for specific key

I have an array and I am checking if a value exists in the array using in_array(). However, I want to check only in the ID key and not date.

$arr = ({
    "ID":"10",
    "date":"04/22/20"
},
{
    "ID":"20",
    "date":"05/25/20"
},
{
    "ID":"32",
    "date":"07/13/20"
});

So in this example, the condition should not be met since 25 exists in date, but not in ID.

if (in_array("25", $arr)) {
    return true;
}

Advertisement

Answer

To directly do this, you need to loop over the array.

function hasId($arr, $id) {
    foreach ($arr as $value) {
        if ($value['ID'] == $id) return true;
    }
    return false;
}

If you need to do this for several IDs, it is better to convert the array to a map and use isset.

$map = array();
foreach ($arr as $value) {
    $map[$value['ID']] = $value;
    // or $map[$value['ID']] = $value['date'];
}

if (isset($map["25"])) {
    ...
}

This will also allow you to look up any value in the map cheaply by id using $map[$key].

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement