Nita Nita - 1 month ago 17
PHP Question

PHP foreach filtered by condition

I have multidimensional array with results and I would like to filter these based on given category. Just like we would do with “WHERE” in MySQL.

<?php
$links_cat = 1;
foreach($linkcreator as $x=>$link)
{
echo "Category: " . $link[0] . " - <a href='" . $link[1] . "'>" . $link[2] , "</a>";
echo "<br>";
}
?>


$links_cat
is corresponding with
$link[0]
. How do I achieve that?

Answer

With an if statement

<?php 
$links_cat = 1;
foreach($linkcreator as $x=>$link)
{
    if($link[0] == $links_cat){
        echo "Category: " . $link[0] . " - <a href='" . $link[1] . "'>" . $link[2] , "</a>";
        echo "<br>";
    }
}
?>
Comments