Invalid argument foreach () return blank message

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/user/public_html/script.php

How do I change the code to write: "Not available"? Can anyone help?

    
asked by anonymous 07.08.2017 / 23:10

2 answers

4

You can check the array before going to 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>';
}
    
07.08.2017 / 23:16
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;?>
    
07.08.2017 / 23:26