Search code examples
phpmysqlif-statementselect-options

Select option still appears on the page even after PHP IF.. statement


I'm developing an Online Store with PHP, so at the productdetails.php which shows the details of products, I coded this:

if(!empty($pro_colors))
{
echo "
    <div class=''>
        <h4 class='' style='float:right'>&nbsp;:رنگ <span>*</span></h4>
        <select class='select-css'>      
        ";
        foreach($pro_colors as $colors)
        {
            echo "
                <option value='$colors'>$colors</option>
            ";                                          
        }
        echo "
        </select>
    </div></br>
";
}

So simply what it should do is that, if any color has been added to the product at db, it has to show the select option and if no color has been added to the db, the select option must not appear!

But when there is not data on db as color, it shows this:

enter image description here

However, my table looks like this:

enter image description here

So please tell me, how should I solve this problem ?!


Solution

  • It seems your array $pro_colors has an empty value. You can clean empty and null values from your array using array_filter

    $pro_colors = array_filter($pro_colors);
    
    if(!empty($pro_colors))
    {
    echo "
        <div class=''>
            <h4 class='' style='float:right'>&nbsp;:رنگ <span>*</span></h4>
            <select class='select-css'>      
            ";
            foreach($pro_colors as $colors)
            {
                echo "
                    <option value='$colors'>$colors</option>
                ";                                          
            }
            echo "
            </select>
        </div></br>
    ";
    }