0

I have this array:

$array = array(
    ['name' => 'Indor Swimming Pool'],
    ['name' => 'abracadabra'],
);

I want sort if alphabetically, so I did:

usort($array, function($a, $b)
{
    return strcmp($a['name'], $b['name']);
});

but when I dump it:

var_dump($array);

I get:

array(2) {
  [0]=>
  array(1) {
    ["name"]=>
    string(19) "Indor Swimming Pool"
  }
  [1]=>
  array(1) {
    ["name"]=>
    string(11) "abracadabra"
  }
}

this is incorrect, abracadabra should go as first

  • 2
    Does this answer your question? [How to Sort Multi-dimensional Array by Value?](https://stackoverflow.com/questions/2699086/how-to-sort-multi-dimensional-array-by-value) – wanjaswilly May 26 '20 at 10:00
  • @Legeekthe_dev unfortunately not, the array is not sorted alphabetically – the_only_one May 26 '20 at 10:10
  • 2
    The result you are getting _is_ correct, for the _case sensitive_ comparison you are doing here. If you want a case insensitive comparison - then use `strcasecmp`. – CBroe May 26 '20 at 10:41

2 Answers2

1

According to the ASCII table chr I comes first and then comes the a chr

ASCII Table

So here your array is actually getting sorted alphabetically to achieve the desired result you need to sort the array in the descending order

<?php
$data = array(
    ['name' => 'Indor Swimming Pool'],
    ['name' => 'abracadabra'],
);
arsort($data);
?>

Output

Array
(
    [1] => Array
        (
            [name] => abracadabra
        )

    [0] => Array
        (
            [name] => Indor Swimming Pool
        )

)
Kunal Raut
  • 2,495
  • 2
  • 9
  • 25
0

It works as intended. The reason for this order is that 'a' is actually after 'I' in ASCII.

matek997
  • 349
  • 1
  • 12