Christian Igay
Christian Igay

Reputation: 35

How to sort array with special characters or numbers in PHP?

I having problems on sorting array. My code works on numbers but is not working well on special characters. I tried also with strcmp() function but no luck. Here is my code:

$sortBy = $this->input->get('sortBy') !== NULL ? $this->input->get('sortBy') : "";
$arr_ongoing = $this->getArr($this->array_ongoing, "id");
setlocale(LC_ALL, "fr-FR");
usort($arr_ongoing, function ($a, $b) use($sortBy) {
    return strcoll($a[$sortBy], $b[$sortBy]); 
});

here is my sample array: Array ( 1 => Array ( [arrete_id] => 1 [etude_id] => 458 [lastname] => Chambre test [crpcen] => 29000 [ville] => Quimper )

[2] => Array
    (
        [arrete_id] => 2
        [etude_id] => 361
        [lastname] => PICART et Associé(s)
        [crpcen] => 44007
        [ville] => NANTES
    )

[3] => Array
    (
        [arrete_id] => 3
        [etude_id] => 35
        [lastname] => JARNOUEN de VILLARTAY et REGEON-VERGNOUX - SE
        [crpcen] => 22005
        [ville] => SAINT-BRIEUC CEDEX 2
    )

[12] => Array
    (
        [arrete_id] => 12
        [etude_id] => 132
        [lastname] =>  LE PAPE et LACOURT
        [crpcen] => 29022
        [ville] => PONT-L'ABBE CEDEX
    )

[13] => Array
    (
        [arrete_id] => 13
        [etude_id] => 222
        [lastname] => KERJEAN et Associé(s)
        [crpcen] => 35129
        [ville] =>  BRUZ CEDEX
    )

)

output

Upvotes: 1

Views: 624

Answers (1)

Bartosz Pachołek
Bartosz Pachołek

Reputation: 1308

If by "special chars" you mean chars specific to a particular language I suggest using Collator from the intl package of extensions.

For example for Polish standard sort of:

$array = [ 'a', 'ą', 'b', 'z' ];

will give you:

array(4) {
  [0] =>
  string(1) "a"
  [1] =>
  string(1) "b"
  [2] =>
  string(1) "z"
  [3] =>
  string(2) "ą"
}

while sorting using Collator the correct one:

$collator = new Collator('pl_PL');
$collator->sort($array);

gives the correct:

array(4) {
  [0] =>
  string(1) "a"
  [1] =>
  string(2) "ą"
  [2] =>
  string(1) "b"
  [3] =>
  string(1) "z"
}

If you cannot use the pecl intl but using PHP >=7.0.0 you can use this lib: https://github.com/voku/portable-utf8

for example:

$array = [ 'a', 'ą', 'b', 'z' ];

function mysort($a, $b) {
    return UTF8::strcmp($a, $b);
}

use voku\helper\UTF8;
usort($array, 'mysort');


It does not require mbstring or intl to be installed (although suggests it).

You should not rely on setlocale as it is based on the locales installed in the particular system and those may not only be not installed, but also their names may differ (between Windows and *nix, but also between *nixes).

Upvotes: 1

Related Questions