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?
Build up an array, and then use implode
:
$parts = array();
foreach($arr as $key=>$value) {
$parts[] = process($key, $value);
}
$outString = "[". implode(", ", $parts) . "]";
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 ", "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With