Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array with PHP, ignoring the (Mr, Mrs) or Some articles

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,
);
like image 842
KARTHI SRV Avatar asked Feb 07 '23 00:02

KARTHI SRV


1 Answers

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));
          });
like image 66
splash58 Avatar answered Feb 10 '23 11:02

splash58