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; } 
Add Comment
3 Answer(s)

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

Add Comment

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.

Answered on July 16, 2020.
Add Comment

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'; }; 
Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.