Search code examples
phparraysasort

Add element to array after sorting


How to add element to begining array after asort() With keeping keys?

$array = array(
    564 => "plum",
    123 => "apple",
    543 => "lemon",
    321 => "cherry",
    );
    asort($array);
    $array[0]="all";
    print_r($array);

I get, index of key [0] is not at the beginig

Array(
[123] => apple
[321] => cherry
[543] => lemon
[564] => plum
[0] => all )

Need

Array(
[0] => all    
[123] => apple
[321] => cherry
[543] => lemon
[564] => plum)

Solution

  • $array = array(
        564 => "plum",
        123 => "apple",
        543 => "lemon",
        321 => "cherry",
    );
    $array[0]="all";
    uasort($array, function($a, $b) {
      if ($a === 'all') return -1;
      return strcmp($a, $b);
    });
    print_r($array);