Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array() expects parameter 2 to be array, integer given

Tags:

arrays

php

I want to create an overview of the first dates of every event. So the event-title must be unique. My idea was to create a helper-function where I loop over the result of my query and check the title of every item. To make sure every title passes only once, I want to push the title into an array ($checklist). If it does not exist, I add that item to the result-array. If it does, just continue to the next item.

I always get the error:

in_array() expects parameter 2 to be array, integer given

This is my code:

function showFirstEvenst($collection) {
    $checklist = array();
    $result = array();

    foreach ($collection as $item) {
        $title = strtolower($item['events']['title']);

        if (!in_array($title, $checklist)) {
            $checklist = array_push($checklist, $title);
            $result = array_push($result, $item);
        }
    }

    return $result;
}

I already tried to cast $checklist and $result as array in the foreach loop but without result.

What do I need to change?

like image 314
bflydesign Avatar asked Jun 12 '26 06:06

bflydesign


1 Answers

Adding to @Lawrence Cherone and @Ravinder Reddy's answers, instead of using array_push, you could use native array syntax to push to the array:

if (!in_array($title, $checklist)) {
    $checklist[] = $title;
    $result[] = $item;
}
like image 151
Graham S. Avatar answered Jun 13 '26 19:06

Graham S.