Skip to content
Advertisement

Search for an item in inner array

I have an assoc array looking like this (the data comes from user input, this is just an example)

$startingDate = "2020-10-20";
$daysBetween[] = "2020-10-21", "2020-10-22", "2020-10-23";
$endingDate = "2020-10-24";
$eventDates[ID] => [
     "startingDate" => $startingDate,
     "daysBetween"  => $daysBetween,
     "endingDate"   => $endingDate, 
];

How would I look for a specific startingDate for example if I don’t want to loop over every ID. Basically I’m looking for a way to do something like $eventDates[*]["startingDate"]

Advertisement

Answer

You can achieve this a few different ways, one being array_filter().

$searchFor = '2020-09-20';
$result = array_filter($eventDates, function($v) use ($searchFor) {
    return ($v['startingDate'] ?? null) == $searchFor;
});

This returns the array(s) where you match the $searchFor variable with a column startingDate. If you just want the first one, use $result = array_shift($result); to get the first one.

This approach basically filters out any results where the callback doesn’t return true. By including use ($searchFor) the variable becomes visible inside the scope of that function, otherwise it would be undefined within that scope.

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