0

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;
}
2
  • Loop over the array. Commented Jul 13, 2020 at 17:10
  • Shortcut way could be passing array_column() result to the in_array() function. Like, in_array("25", array_column($arr, 'ID')). Clean, yes. Efficient, not much. Commented Jul 13, 2020 at 17:24

3 Answers 3

1

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].

Sign up to request clarification or add additional context in comments.

Comments

1

For versions of PHP (>= 5.5.0), there is a simple way to do this

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

$searched_value = array_search('25', array_column($arr, 'ID'));

Here is documentation for array_column.

Comments

0

You can also check it by array_filter function:

$searchId = '25';
$arr = [[
    "ID" => "10",
    "date" => "04\/22\/20"
],
[
    "ID" => "25",
    "date" => "05\/25\/20"
],
[
    "ID" => "32",
    "date" => "07\/13\/20"
]];

$items = array_filter($arr, function ($item) use ($searchId) { 
    return $item['ID'] === $searchId;
});

if (count($items) > 0) {
   echo 'found';
};

2 Comments

This is more expensive than simply looping over the array, as it creates an entirely new array you do not need.
@AliceRyhl I have added also here) If just need to check the existence of the item then simple loop and return immediately would be efficient

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.