function sortByName($a, $b) { if ($a[1] == $b[1]) { return 0; } return ($a[1] < $b[1]) ? -1 : 1; } usort($res, "sortByName"); 

Will this function work correctly?

in $res array of names like:

['file1.txt'. 'abf.txt' ...]

  • one
    give an example of an array body. what is inside and in what form. - Lexx918
  • We'll have to change if ($a[1] == $b[1]) { return 0; } if ($a[1] == $b[1]) { return 0; } on if ($a == $b) {return 0; } if ($a == $b) {return 0; } - And
  • Yes, apparently. Accordingly, changed and return ($a < $b) ? -1 : 1; return ($a < $b) ? -1 : 1; - Timur Musharapov
  • 2
    You are now sorting by the second letter of the array element. Take It Everywhere [1] - rjhdby

1 answer 1

For such an array, the finished function natcasesort () is most likely suitable for you, or one of the usual sorting options with the sort () flag you need. I don’t see any sense in making a fuss out of my own comparator.

upd .: but if sooooo want exactly your comparison function, then just put one line return strcmp($a, $b) in its body. The strcmp function can be replaced with any other suitable one (they are listed at the end of the article for this link). In the 7th puff, you can also find a trendy space thorn operator to return $a <=> $b .

  • Thanks for the detailed answer. - Timur Musharapov