Home > Blockchain >  foreach loop doesn't print result nor show error on PHP 8
foreach loop doesn't print result nor show error on PHP 8

Time:11-24

I just migrated to php 8 and I have code that looks like below, it doesn't work and it doesn't show errors.

<?php
ini_set('display_errors', 1);
error_reporting(~0);
$list = array(
    array(
        "id" => 0
    ),
    array(
        "id" => 20
    )
);
?>
<div>MORE HTML</div>
<div>
     <?php foreach($list as $k => $row){  ?>
        /*<?php echo $row["id"];?> This line alone works*/
        <div> 
            <div>MORE HTML</div>
            <?php if($row["id"] >= 10){ ?>
               This  should show   
               <div>MORE HTML</div>       
            <? } ?>
        </div>
        <div>MORE HTML</div>
     <?php } ?>
     <div>MORE HTML</div>
</div>

CodePudding user response:

That's because you are missing php keyword on line 17. Should be <?php } ?>

So the full syntax is:

 <?php
    ini_set('display_errors', 1);
    error_reporting(~0);
    $list = array(
        array(
            "id" => 0
        ),
        array(
            "id" => 20
        )
    );
    ?>
    <?php foreach($list as $k => $row){  ?>
            /*<?php echo $row["id"];?> This line alone works*/
            <?php if($row["id"] >= 10){ ?>
                This  should show          
            <?php } ?>
    <?php } ?>

CodePudding user response:

This works for me in PHPv8.0.13

Just add the echo echo $row["id"];

<?php
ini_set('display_errors', 1);
error_reporting(~0);
$list = array(
    array(
        "id" => 0
    ),
    array(
        "id" => 20
    )
);

foreach($list as $k => $row){
    // echo $row["id"]; // This line alone works
    if($row["id"] >= 10){
        // This  should show     
        echo $row["id"];
    }
}
?>

See it life: https://3v4l.org/s5LkO#v8.0.13

CodePudding user response:

Check it out with PHP sandbox: https://sandbox.onlinephpfunctions.com/

Your code is working for me.

I recommend you check the errors logs of the server.

  • Related