phparraysforeachfilteringwhitelist

Only print array row data if id is found in a whitelist array


I have a list of categories for my videos, and with this simple foreach loop, I'm displaying all of them inside hyperlinks.

Now, what I want to do is display only some of them, based on the category ID.

Code that display all the categories:

$idx = 0;

foreach ($this->categories as $category) 
{
    echo "\n" . ($idx++ ? '| ' : '') . '<a href="' . KM_Helpers::getCategoryURL($category) . '">' . $category['name'] . '</a>';
}

Let's say now I want to display only the categories with the ids: 2,8,21,22. I can use $category['id'] to get the IDS.

I was thinking of having an array that contains only the ID I want to show...

$myarray = array(2, 8, 21, 22);

My question is, how can I loop in my $category array, displaying only the ID contained in the array? (Based on $category['id'] )


Solution

  • $idx = 0;
    $myarray = array(2, 8, 21, 22);
    foreach($this->categories as $category) 
    {
        if (!in_array($category['id'], $myarray)) {
            continue; // skip it if the id isn't in your array of accceptable IDs
        }
        echo "\n".($idx++ ? '| ' : '').'<a href="'.KM_Helpers::getCategoryURL($category).'">'.$category['name'].'</a>';
    }