-1

This is my code:

$sm2 = array( "angry", "cool", "cry", "happy", "heart", "kiss", "mute", "sad", "smile"); 

for($j=0;$j<count($sm2); $j++) {
    $data=$data . "<img id='". $sm2[$j] ."' src='images/emotions/" . $sm2[$j] . ".png' data-toggle='tooltip' title=". $sm2[$j] ."  width='32' height='32' style='margin:5px;'
    onclick='insertEmoticons(this.id);'/>";
}

How can I insert a <br> tag after 5 results because i don't want everything to be on one row.

Mensur
  • 457
  • 9
  • 28
  • modulus `($i % 5 == 0)` - as per http://stackoverflow.com/questions/8135404/php-modulus-in-a-loop which this is also a possible duplicate – Funk Forty Niner Jul 30 '16 at 01:58

2 Answers2

2

Use the Modulus operator.

<?php
$sm2 = array( "angry", "cool", "cry", "happy", "heart", "kiss", "mute", "sad", "smile"); 
for($j=0;$j<count($sm2); $j++) {
     if(!empty($j) && $j % 5 == 0) {
          echo '<br>';
     }
     echo $sm2[$j];
}

Output:

angrycoolcryhappyheart<br>kissmutesadsmile

Demo: https://eval.in/614166

Or with your actual code:

for($j=0;$j<count($sm2); $j++) {
    if(!empty($j) && $j % 5 == 0) {
          $data .= '<br>';
    }
    $data=$data . "<img id='". $sm2[$j] ."' src='images/emotions/" . $sm2[$j] . ".png' data-toggle='tooltip' title=". $sm2[$j] ."  width='32' height='32' style='margin:5px;'
    onclick='insertEmoticons(this.id);'/>";
}

Also note $data=$data . is the same as $data .= ....

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
chris85
  • 23,846
  • 7
  • 34
  • 51
0
$sm2 = array( "angry", "cool", "cry", "happy", "heart", "kiss", "mute", "sad", "smile"); 

for($j=0;$j<count($sm2); $j++) {
    $data=$data . "<img id='". $sm2[$j] ."' src='images/emotions/" . $sm2[$j] . ".png' data-toggle='tooltip' title=". $sm2[$j] ."  width='32' height='32' style='margin:5px;' onclick='insertEmoticons(this.id);'/>";
    if ( (($j+1) % 5) == 0)
    {
        $data = $data . "<br>";
    }

}
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40