简体   繁体   中英

PHP table alignment is not correct inside foreach Loop

I want to display Array data in a table with 3 columns in a row using foreach loop with a condition.

Coding

$value[]='a';
$value[]='b';
$value[]='c';
$value[]='d';
$value[]='e';

echo '<table width=30% border=1>';  
    echo '<tr>';
        $counter=1; 

        foreach($value as $key){
            if($counter>=3){ // if there is more than 3 elements, go to next Row

                    if($counter%3==0){ // when the Array hit 3th,6th,9th,12th.... element
                        echo '</tr><tr><td>';               
                        echo $key;  
                        echo '</td>';                   
                    }else{
                        echo '<td>';
                        echo $key;              
                        echo '</td>';                       
                    }
            }else{
                echo '<td>';                
                echo $key;      
                echo '</td>';                   
            }           
            $counter++;
        }
    echo '</tr>';
echo '</table>';

I double check the coding and didn't manage to find the error.... my output is the bottom of the image. However, the correct one should be top of the image. Please take a look at the photo

在此处输入图片说明

Anyone know what's wrong with my coding?

Change modulas condition with

if($counter % 3 == 1)

and you will get what you desire

您具有“ if counter> = 3”,因此您在第三个元素上而不是在第三个元素之后达到该条件。

将计数器的初始化更改为$counter=0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM