G2 Jakhmola
G2 Jakhmola

Reputation: 811

Sort a flat array ascending

$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

Answers (4)

Saurabh
Saurabh

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

chongsong
chongsong

Reputation: 11

var_dump( array_reverse($array,false));

you don't need to use foreach or sort ,you can just use array_reverseinstead ,avery simple way

Upvotes: 0

offchance
offchance

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

Mohd Abdul Mujib
Mohd Abdul Mujib

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

Related Questions