tags:

views:

64

answers:

2

I have a loop spitting out values and are put into a string:

$all_values = "";
while loop {
  $value = "...";
  $all_values .= $value . ",";
}

Output: 1,3,8,2,10...

What's the simplest way to output the same thing but numbers in reverse so the above example would come out like ...10,2,8,3,1

+6  A: 

Put everything into an array and then join it together, reversed:

$all_values = array();
while loop {
  $value = "...";
  $all_values[] = $value;
}
$all_values = implode(',', array_reverse($all_values));

This is also more efficient if there are millions of values.

too much php
+1: Even if you don't need to reverse the values, this would still be faster. String concatenation is slow due to the mutability of strings requiring the string to be read and re-created for every concatenation.
Blixt
+1  A: 

Add after your code:

$ar = explode(',', $all_values);
$revAr = array_reverse($ar);
$all_values = implode(',', $revAr);
RaYell