Solution 1 :

You can also make use of array_chunk to decide the chunk(no. of times) for each row and repeat a string using str_repeat the chunk size times to achieve your goal.


$times = 12;
$limit_for_each_row = 5;
$string = "Cat";

echo "<table>";
foreach(array_chunk(range(1,$times),$limit_for_each_row) as $chunk){
    echo "<tr>" . str_repeat("<td>$string</td>",count($chunk)) . "</tr>";
echo "</table>";


Solution 2 :

May following code will help you to achieve requested output:

$print_label = "meow";
$q = 15;
$steps = 5;

echo "<table>";
for($i=1;$i<=ceil($q/$steps);$i++) :
    echo "<tr>";
    for($j=1;$j<=$steps;$j++) :
        echo "<td>".$print_label."</td>";
    echo "</tr>";
echo "</table>";

Solution 3 :

One way to solve this problem is by using array_fill to make an array of $q copies of the word; array_chunk to split that into the maximum number of words per row; and implode to put all the words in each chunk together into a row:

$word = "cat";
$q = 13;
$row_max = 5;
$words = array_fill(0, $q, $word);
$chunks = array_chunk($words, $row_max);
foreach ($chunks as $chunk) {
    echo '<tr><td>' . implode('</td><td>', $chunk) . '</td></tr>' . "n";



Demo on

Problem :

i have a variable Q,
i want to print “cat” (or whatever) Q times in HTML table rows, only each row of the HTML table can contain maximum of 5 cats.
like if Q <= 5 then i want to print a single <tr>.
& if Q = 10;
then i want to print 2 rows each containing 5 cats.

can someone help me here?

I’m using php as the programming language and HTML.
thanks in advance.


Comment posted by Mikkel

Please have a go at writing the code yourself, and we’ll help you make it work

Comment posted by Milon Hossain

Appreciate your help <3