Search code examples
phpdebuggingif-statementnested-loops

PHP- How to solve else in nested foreach loop


This my code syntax all conditions are working but last else is not working. I found solution in there https://stackoverflow.com/a/5930255/7688968 and I am used break 2 but still not working. How can I solve that?

<?php
$rows = $wpdb->get_results( "SELECT * FROM test WHERE approve_status = '1'" );

if($rowcount>0)
{
    foreach ($rows as $row)
    { 
        if ( is_user_logged_in() ) 
        {
            echo 'I am user';
            $demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");

            foreach($demo as $demos)
            {

                if(!empty($demos->id)){
                    echo 'I am IF';
                     break 2;
                }

                else{
                    echo  'I am last ELSE';
                }
            }
        }
        else{
            echo 'I am guest user';
        }
    }
}

Solution

  • You are doing the else in the wrong place, it should be done instead of the foreach...

       $demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");
    
        if(!empty($demo)){
            foreach($demo as $demos)
            {
                echo 'I am IF';
            }
        }
        else{
            echo  'I am last ELSE';
        }
    

    So the logic is that if no records are returned then display your message.