Reputation: 811
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
Array
(
[0] => 5
[1] => 4
[2] => 1
[3] => 2
)
Expecting result
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
)
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
$results = [];
foreach($array as $key=>$value){
$results[$key] = arsort($value);
}
echo "<pre>";
print_r($results);
Please suggest how do we can sort associative array i did try but does not work for me please guide
Upvotes: 1
Views: 60
Reputation: 784
You don't need to iterate using foreach for sorting
Just use sort
for sorting array
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
This will not maintain array keys and if you want arrays keys to be same just replace sort
with asort
in above code
Upvotes: 0
Reputation: 11
var_dump( array_reverse($array,false));
you don't need to use foreach or sort ,you can just use array_reverse
instead ,avery simple way
Upvotes: 0
Reputation: 682
Just do
sort($array);
Also check the PHP documentation if you need further customization: http://php.net/manual/en/function.sort.php
Upvotes: 0
Reputation: 13948
As per your "expected results' it seems like you don't wish to maintain the keys
. If that's the case then you can just use sort
.
Something like this..
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
Upvotes: 2