Brad Fletcher
Brad Fletcher

Reputation: 3593

Is there a better way to do this in PHP

i am using this code to generate rows depending on the value in the database, I'm sure there is a more efficient way of doing this but I'm unsure how!

if ($empty == 1) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
if ($empty == 2) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
if ($empty == 3) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
if ($empty == 4) {
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
    echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}

Upvotes: 4

Views: 176

Answers (3)

Justinas
Justinas

Reputation: 43441

You can use str_repeat for that:

if ($empty > 0) {
    echo str_repeat("<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>", $empty);
}

Upvotes: 14

xAqweRx
xAqweRx

Reputation: 1236

As I can see from your question, you need use a loop :

<?php
  $empty = 4;
  for( $i = 0; $i < $empty; $i ++){
   echo "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
  }

This code will show as many empty rows as you need. And $empty is count of them.

Upvotes: 1

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

You can do it using for loop:

$empty = 5;
$str = '';
for(i=0;$i<$empty;$i++) {
    $str .= "<li class='col-sm-4'><div class='horse-wrap empty'>Empty</div></li>";
}
echo $str;

Upvotes: 15

Related Questions