PHP - when using foreach to loop through an array, how can I find out if I hit the last pair?

I am trying to "pretty-print" 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 drawback of this method is that it will show "," at the end of the printout of the array before closing "]". Is there a good way to use the $ key => $ value syntax to determine if you are in the last pair in an array or should I switch to a loop using each() instead?

+6
loops php foreach
source share
8 answers

Create an array and then use implode :

 $parts = array(); foreach($arr as $key=>$value) { $parts[] = process($key, $value); } $outString = "[". implode(", ", $parts) . "]"; 
+12
source share

You can simply trim the last "," when a substring is used to complete.

 $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 ", " 
+4
source share

Do the processing separately, and then use implode() to join:

 $outArr = array(); foreach($arr as $key => $value) { $outArr[] = process($key, $value); } $outString = '[' . implode(', ', $outArr) . ']'; 
+4
source share

Regardless of the circumstances of your example (combining strings with commas for which implode is the right way) to answer your specific question, the canonical way to iterate through the array and check if you are using the last element, CachingIterator :

 <?php $array = array('k'=>'v', 'k1'=>'v1'); $iter = new CachingIterator(new ArrayIterator($array)); $out = ''; foreach ($iter as $key=>$value) { $out .= $value; // CachingIterator->hasNext() tells you if there is another // value after the current one. if ($iter->hasNext()) { $out .= ', '; } } echo $out; 
+3
source share

It might be easier to do so, and add a comma to the line before the element, if it is not the first element.

 $first= true; foreach ($arr as $key => $value) { if (! $first) { $outString .=', '; } else { $first = false; } //add stuff to $outString } 

Is the output format is JSON? If so, you can use json_encode() instead.

+2
source share

You can do it like a regular loop:

 $outString = "["; for ($i = 0; $i < count($arr); $i++) { // Do stuff if ($i != count($arr) - 1) { $outString += ", "; } } 

However, the best way to do this, IMHO, is to store all the components in an array and then explode:

  $outString = '[' . implode(', ', $arr) . ']'; 

implode () takes all the elements in the array and concatenates them into a string separated by its first argument.

+1
source share

There are many possibilities. I think this is one of the easiest solutions:

 $arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g'); echo '[', current($arr); while ($n = next($arr)) echo ',', $n; echo ']'; 

Outputs:

 [a,b,c,d,e,f,g] 
+1
source share

I try to avoid using loops in such situations. You should use implode () to combine lists with a common separator and use array_map () to handle any processing in this array before combining. Pay attention to the following implementations, which should express the universality of these functions. An array map can take a string (function name) representing either a built-in function or a user-defined function (first 3 examples). You can pass it a function using create_function () or pass a lambda / anonymous function as the first parameter.

 $a = array(1, 2, 3, 4, 5); // Using the user defined function function fn ($n) { return $n * $n; } printf('[%s]', implode(', ', array_map('fn', $a))); // Outputs: [1, 4, 9, 16, 25] // Using built in htmlentities (passing additional parameter printf('[%s]', implode(', ', array_map( 'intval' , $a))); // Outputs: [1, 2, 3, 4, 5] // Using built in htmlentities (passing additional parameter $b = array('"php"', '"&<>'); printf('[%s]', implode(', ', array_map( 'htmlentities' , $b, array_fill(0 , count($b) , ENT_QUOTES) ))); // Outputs: [&quot;php&quot;, &quot;&amp;&lt;&gt;] // Using create_function <PHP 5 printf('[%s]', implode(', ', array_map(create_function('$n', 'return $n + $n;'), $a))); // Outputs: [2, 4, 6, 8, 10] // Using a lambda function (PHP 5.3.0+) printf('[%s]', implode(', ', array_map(function($n) { return $n; }, $a))); // Outputs: [1, 2, 3, 4, 5] 
+1
source share

All Articles