Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - when using foreach to loop through array, how can I tell if I'm on the last pair?

Tags:

loops

foreach

php

I'm trying to 'pretty-print' out an array, using a syntax like:

$outString = "[";
foreach($arr as $key=>$value) {
    // Do stuff with the key + value, putting the result in $outString.
    $outString .= ", ";
}
$outString .= "]";

However the obvious downside of this method is that it will show a "," at the end of the array print out, before the closing "]". Is there a good way using the $key=>$value syntax to detect if you're on the last pair in the array, or should I switch to a loop using each() instead?

like image 994
Stephen Avatar asked Aug 18 '10 12:08

Stephen


2 Answers

Build up an array, and then use implode:

$parts = array();
foreach($arr as $key=>$value) {
    $parts[] = process($key, $value);
}

$outString = "[". implode(", ", $parts) . "]";
like image 182
Dominic Rodger Avatar answered Oct 15 '22 06:10

Dominic Rodger


You can just trim off the last ", " when for terminates by using substring.

$outString = "[";
foreach($arr as $key=>$value) {
  // Do stuff with the key + value, putting the result in $outString.
  $outString .= ", ";
 }

 $outString = substr($outString,-2)."]";  //trim off last ", "
like image 45
Chris Avatar answered Oct 15 '22 04:10

Chris