0

Suppose there is a number of item in array.which may be odd or even like I have an array which contain item from a to z Now I want to display that item in table . But As you know That There are 23 alphabets I want to display these alphabets in table which contains only 5 column in the last you got only three alphabets I want to display them in table . In the last I want that there should be three column not 5.

Here is my code i could not get that what should i do?

But the problem I faced in the below code is that the second loop is not correct.

<?php
$arr=array('a','b','c','d','e','f','g','h');
$count=  sizeof($arr);
$row=ceil($count/5);
echo "<table border='1'>";
for($r=0;$r<$row;$r++){    
echo "<tr>";
    for($j=0;$j<=5;$j++){
    echo "<td>'".$arr[$j]."'</td>";
    }

echo "</tr>";

}
echo "</table>";
?>
1
  • you are getting two rows and 6 columns as i tested, now can you tell me what should be expected result Commented Aug 19, 2016 at 9:41

2 Answers 2

3

My approach uses array_slice to take out pieces of the source and build rows:

$arr=array('a','b','c','d','e','f','g','h');

$offset = 0; 
$num_columns = 5; //adjust number of columns
$table_html = "<table border='1'>";
while($slice = array_slice($arr,$offset,$num_columns)){
    $offset += $num_columns;
    $row_html = '';
    foreach($slice as $n) $row_html .= "<td>$n</td>";
    $table_html .= "<tr>$row_html</tr>";
}
$table_html .= '</table>';
echo $table_html;

Live demo

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Try below code. Declaring number of column required in a variable, so which can be changed any time. closing the tr tag when loop count is same as number of columns to be displayed.

<?php
$arr=array('a','b','c','d','e','f','g','h');
$columnLength = 5;
echo "<table border='1'>";
echo "<tr>";
for($r=0;$r<count($arr) ; $r++){
    echo "<td>'".$arr[$r]."'</td>";
    if($r + 1 ==  $columnLength ) {
        echo "</tr>";
    }
}
echo "</table>";
?>

3 Comments

This does not generate valid table HTML because you have no opening or closing <tr> in the second row
@BeetleJuice, i inspected the elements generated by the code above and second row does have opening and closing <tr>. I liked your approach, but have a doubt. That is can we get desired output by avoiding an extra loop ??
Hey Sameer :-) You see all the tags in the browser's DOM inspector because the browser adds the missing tags for you. Here is what the raw output of your code looks like: 3v4l.org/g8dK2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.