0

I tried to use for-loop/foreach inside array_filter(). but the for loop/foreach doesn't work inside array_filter(). How can I use for-loop/foreach inside array_filter()?

$bookingData = array_values(array_filter($jsonBooking, function($bookingItem) {
    foreach ($orderData as $orderItem) {
        if ($bookingItem['order_id'] === $orderItem['id']) { 
            return $bookingItem;
        }
    }
}
1
  • 2
    The answer given does solve the problem, even while it looks like there are much better ways of doing this. But without more context from your side, I don't care to speculate. Also, your return bookingItem should have had a $, and that should have given an error for "undefined constant". Along with the fact that $orderData was undefined. Are you developing without error reporting on? Commented Mar 5, 2022 at 16:24

1 Answer 1

2

Callback inside array_filter must returns bool (as condition to filter), be but you return an object. This should work.

$bookingData = array_values(array_filter($jsonBooking, function($bookingItem) use ($orderData) {
    foreach ($orderData as $orderItem) {
        if ($bookingItem['order_id'] === $orderItem['id']) { 
            return true;
        }
    }
    return false;
}

UPDATED: don't forget use statement

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

1 Comment

$orderData is unknown inside filter. // GG I reversed my vote

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.