Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php alphabetically order an array by last word in string

Tags:

arrays

php

I have an array. eg:

names = {
    'John Doe',
    'Tom Watkins',
    'Jeremy Lee Jone',
    'Chris Adrian'
    }

And I want to order it alphabetically by last name(last word in string). Can this be done?

like image 557
Cybercampbell Avatar asked Jan 13 '23 12:01

Cybercampbell


2 Answers

$names = array(
    'John Doe',
    'Tom Watkins',
    'Jeremy Lee Jone',
    'Chris Adrian',
);

usort($names, function($a, $b) {
    $a = substr(strrchr($a, ' '), 1);
    $b = substr(strrchr($b, ' '), 1);
    return strcmp($a, $b);
});

var_dump($names);

Online demo: http://ideone.com/jC8Sgx

like image 50
zerkms Avatar answered Jan 22 '23 17:01

zerkms


You can use the custom sorting function called usort (http://php.net/manual/en/function.usort.php). This allows you create a comparison function which you specify.

So, you create a function like so...

function get_last_name($name) {
    return substr($name, strrpos($name, ' ') + 1);
}

function last_name_compare($a, $b) {
    return strcmp(get_last_name($a), get_last_name($b));
}

and you make the ultimate sort using usort using this function:

usort($your_array, "last_name_compare");
like image 38
Grumpy Avatar answered Jan 22 '23 18:01

Grumpy