Search code examples
phparraysloopskeyfiltering

Using a for() loop after array_filter() gives Warning: Undefined array key


I'm using array_filter with multiple parameters but it's not doing the filter correctly. Here where it's supposed to return an array with only "arts,crafts,designs" as an element, it's returning an empty array. The only $askedcat parameter it works for is "arts". I can't find out what the issue is.

I've tried not using an array_filter and instead just looping over the array, and I get the same problem.

class CategoryFilter {
    public $categoryAskedFor;

    function __construct($askedCat) {
            $this->categoryAskedFor = $askedCat;
    }

    function categoryCallback($projectCategoryString) {
        $project_category_array = explode(",", $projectCategoryString);
        if(in_array($this->categoryAskedFor, $project_category_array)) return true;
        return false;
    }
}

$verifiedProjects = ["arts", "arts,crafts,designs", "film", "film,theater"];

$askedCat = "crafts";

$newArr = array_filter($verifiedProjects, array(new CategoryFilter($askedCat), "categoryCallback"));

for ($i = 0; $i < count($newArr); $i++) {
    echo $newArr[$i] . "<br>";
}

I expect the output here to be arts,crafts,design<br> but it's only <br> meaning the array is empty.


Solution

  • The way you're looping over your resulting array is wrong, because array_filter will preserve the array keys. The 0 index may not be there in the filtered version (and in your case, it actually isn't).

    Use foreach instead:

    foreach ($newArr as $value) {
      echo $value, '<br>';
    }