views:

53

answers:

3

i want to sort an array by alphabet

when i use asort() its sorting , but the results that i get is first of all , the names in upper-case, and after that all the names with lower-case

like :

Avi
Beni
..
..
avi
beni

if i want like :

Avi
avi
Beni
beni
..
..

how can i do it ?

+2  A: 

natcasesort

Sjoerd
thanks its work!
Haim Evgi
It does not work. Try to sort this array: array('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png');
Eineki
+4  A: 

You can use netcasesort(). It sort an array using a case insensitive "natural order" algorithm.

Do it like this:

natcasesort($array);
shamittomar
+1 for adding an actual answer instead of just the link
Gordon
It does not work. Try to sort this array: array('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png');
Eineki
+1  A: 

The proposed solutions, until now, arent correct, natcasesort and the usort($arr, 'strcasecmp') solutions are failing with some starting array configurations.

Let do some tests, to find a solution.

<?php
$array1 = $array2 = $array3 = $array4 = $array5 = array('IMG1.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG2.png');

// This result is the one we nee to avoid
sort($array1);
echo "Standard sorting\n";
print_r($array1);

// img2.png and IMG2.png are not in the desired order
// note also the array index order in the result array
natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);

// img1.png and IMG1.png are not in the desired order
usort($array3, 'strcasecmp');
echo "\nNatural order sorting (usort-strcasecmp)\n";
print_r($array3);

// Required function using the standard sort algorithm
function mySort($a,$b) {
  if (strtolower($a)== strtolower($b))
    return strcmp($a,$b);
  return strcasecmp($a,$b);
}

usort($array4, 'mySort');
echo "\nStandard order sorting (usort-userdefined)\n";
print_r($array4);

// Required function using the natural sort algorithm
function myNatSort($a,$b) {
  if (strtolower($a)== strtolower($b))
    return strnatcmp($a,$b);
  return strnatcasecmp($a,$b);
}

usort($array5, 'myNatSort');
echo "\nNatural order sorting (usort-userdefined)\n";
print_r($array5);

?>

Eineki