Sort an array by using name I had an array.
array(0 => Mr. Bala ,1 => Mr. Santhosh, 2 => Mrs. Camel,3 => Mrs. Vinoth);
Sort it in ascending order based on only Name
My expected output is
array(
0 => Mr. Bala,
1 => Mrs. Camel,
2 => Mr. Santhosh,
3 => Mr. Vinoth,
);
using usort, taking 2nd part of string, splited by point with space after
usort($a, function($i1, $i2) {
return strcmp(explode('. ',$i1)[1], explode('. ',$i2)[1]);
});
UPD due to Bart Friederichs comment
usort($a, function($i1, $i2) {
$t = explode('. ',$i1);
$i1 = (! isset($t[1]) ? $i1 : $t[1]);
$t = explode('. ',$i2);
$i2 = (! isset($t[1]) ? $i2 : $t[1]);
return strcmp($i1, $i2);
});
demo
UPD2 To make it case insensitive
usort($a, function($i1, $i2) {
$t = explode('. ',$i1);
$i1 = (! isset($t[1]) ? $i1 : $t[1]);
$t = explode('. ',$i2);
$i2 = (! isset($t[1]) ? $i2 : $t[1]);
return strcmp(strtoupper($i1), strtoupper($i2));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With