Search code examples
phpsortingalphabetical

How would I sort names (first and last name) alphabetically in PHP, case insensitive?


I am trying to sort an array of student names alphabetically. In the array we have $user['firstname'] and $user['lastname']. I want to sort it such that A/a comes first and then Z/z comes last. If their first names are the same then we compare with last name. My problem is that I've already created the functionality for this sorting but it is not case insensitive.

This is what I've done so far:

uasort($students, array($this, 'nameCompare'));
private function nameCompare($a, $b)
{
    if ($a['firstname'] == $b['firstname']) 
    {
        if($a['lastname'] < $b['lastname'])
        {
            return -1;
        }
        else if ($a['lastname'] > $b['lastname'])
        {
            return 1;
        }
        else //last name and first name are the same
        {
            return 0;
        }
    }
    return ($a['firstname'] < $b['firstname']) ? -1 : 1;
}

Thanks for your help.


Solution

  • I think the strtolower function could be useful. At the beginning of your function just add this:

    $a['firstname'] = strtolower($a['firstname']);
    $a['lastname'] = strtolower($a['lastname']);
    $b['firstname'] = strtolower($b['firstname']);
    $b['lastname'] = strtolower($b['lastname']);
    

    By doing this you convert all values to lower case, removing the "sensitiveness" of the function.

    Hope it helps.