Invalid argument foreach() return empty message

Asked

Viewed 116 times

2

<table border="1">
    <?php
        foreach($arrayReturn['qsa'] as $value){
    ?>
        <tr>
            <td>NOME:</td>
            <td><?=$value['qual'];?></td>
            <td><?=$value['nome'];?></td>
        </tr>


    <?php
        }
    ?>
</table>

It turns out that sometimes there are no values in the database. And I get the following error: Warning: Invalid argument supplied for foreach() in /home/usuario/public_html/script.php

How do I change the code to write: "Not available"? Someone can help?

2 answers

4


You can check the array before going to the foreach

if( is_array($arrayReturn['qsa']) && count($arrayReturn['qsa']) > 0 ) {
    // Aqui continua o seu foreach
}else{
    echo '<tr><td colspan="3">Não Disponível</td></tr>';
}
  • Great Anderson! Perfect!

2

Just check if index exists this way

<?php if(isset($arrayReturn['qsa'])): ?>
     <?php foreach($arrayReturn['qsa'] as $value): ?>
            <tr>
                <td>NOME:</td>
                <td><?=$value['qual'];?></td>
                <td><?=$value['nome'];?></td>
            </tr>
    <?php endforeach;?>
<?php else: ?>

<p>Não disponivel</p>

<?php endif;?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.