Need help with simple question (substr)

Why in loop

  while ($res = mysqli_fetch_assoc($arr)) {	 
     echo $res['num']."|"; 
 }

I see results like

1|17|33|49|65|2|18|34|50|67|3|19|35|51|68|4|20|

But when i do

  while ($res = mysqli_fetch_assoc($arr)) {	 
     $r = $res['num']."|"; 
	 echo substr($r, 0, -1);
 }

It show me results

117334965218345067319355168420

How to do it work fine, like here (remove last character)

1|17|33|49|65|2|18|34|50|67|3|19|35|51|68|4|20

thanks

Put your echo statement outside of the while loop

To add to that, try concatenating inside the loop and rtrim() (or is substr more efficient?) before the echo.

Thanks for all! Work Fine)))

$s = array();
    while ($res = mysqli_fetch_assoc($arr)) {	 
     $s[] = $res;
    }
     echo "".$s['0']['num']."|".$s['1']['num']."|".$s['2']['num']."|".$s['3']['num']."|".$s['4']['num']."|".$s['5']['num']."|".$s['6']['num']."|".$s['7']['num']."|".$s['8']['num']."|".$s['9']['num']."|".$s['10']['num']."|".$s['11']['num']."|".$s['12']['num']."|".$s['13']['num']."|".$s['14']['num']."|".$s['15']['num']."|".$s['16']['num']."";

You can use echo implode('|', $s); instead of that long echo statement.

Example:

$s = array();
    while ($res = mysqli_fetch_assoc($arr)) {	 
     $s[] = $res['num'];
    }
     echo implode('|', $s);
3 Likes

Thanks! This is more effective and beautiful way!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.