Search code examples
phparrayslaravelalphabetical-sort

Is it possible to order an array alphabetically in Laravel?


I am new to Laravel and I was wondering if I can order the following multidimensional array with countries alphabetically? So I want all the countries inside the continents to be ordered alphabetically.

  "EU" => array:9 
    0 => "NL"
    1 => "BE"
    3 => "FR"
    4 => "DE"
    5 => "ES"
    6 => "IT"
    7 => "GB"
    8 => "TR"
    9 => "DK"
  ]
  "AS" => array:2
]

Solution

  • It seems you need to sort an inner array by values. Here is a one way to do it.

    $arr = [
       "EU" => [
            0 => "NL",
            1 => "BE",
            3 => "FR",
            4 => "DE",
            5 => "ES",
            6 => "IT",
            7 => "GB",
            8 => "TR",
            9 => "DK",
      ],
      "AS" => ["AB", "AA"]
    ];
    
    foreach($arr as $continent => $countries) {
        asort($countries);
        $arr[$continent] = $countries;
    }
    
    
    var_dump($arr);