Page 1 of 1

Reversing the order of numbers in a string

Posted: 30 Jul 2015, 07:38
by Marius
Hello
I have a string with these numbers: "3 9 15 23 9 6 8 5", and I want to get a string with reversed order of those numbers.
To get this string: "5 8 6 9 23 15 9 3". Any idea?
Thanks.

Reversing the order of numbers in a string

Posted: 30 Jul 2015, 07:40
by Admin
Hello
See the code from this example. Put the numbers into an array, reverse the array items, then put the reversed numbers into a string.

Code: Select all

$nrs = '3 9 15 23 9 6 8 5';
$ar_nrs = explode(' ', trim($nrs));  //put the numbers into an array
$ar_nrs = array_reverse($ar_nrs);  //reverses the order
$nrs = implode(' ', $ar_nrs);  //put the reversed numbers in string
echo $nrs; // 5 8 6 9 23 15 9 3