Forum Moderators: coopster

Message Too Old, No Replies

how to sort an array? sort() does not work?

         

carsten888

4:43 pm on Aug 8, 2010 (gmt 0)

10+ Year Member



I'm just trying to sort an array.



$arr = array(13, 55, 25);
print_r($arr);
//returns:
//Array ( [0] => 13 [1] => 55 [2] => 25 )

$arr = sort($arr);
print_r($arr);
//returns:
//1





I tried to make a new array out of the object:


$new_arr = array();
foreach($arr as $item){
$new_arr[] = $item;
}




which just gives this error :
Invalid argument supplied for foreach()


What am I overlooking here?

rocknbil

5:40 pm on Aug 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You get a 1 because the function sort() returns true. Do this.

<?php
header("content-type:text/html");
$backward = $arr = array(25, 55, 18, 1);
sort($arr);
rsort($backward);
echo "<br>Sorted Backward:<br>";
print_r($backward);
echo "<br>Sorted Forward:<br>";
print_r($arr);
?>

Works on strings too.

carsten888

8:51 am on Aug 9, 2010 (gmt 0)

10+ Year Member



Thank you! This was driving me nuts! Thank you!