1

I'm looking for a custom function that will respect the order of the array and sort it by the 'name' key. 'strcasecmp()' function doesn't understand alphanueric values as humans would read it. It thinks 'Apples 12' is a lesser value than 'Apples 5'. I tried this method but can't find a function to compare alphanumeric value:

$array = array(
    0 => array(
        'id' => 2,
        'type' => 'Apples',
        'name' => 'Apples 5',
    ),
    1 => array(
        'id' => 3,
        'type' => 'Grapes',
        'name' => 'Apples',
    ),
    2 => array(
        'id' => 4,
        'type' => 'Apples',
        'name' => 'Apples 4',
    ),
    3 => array(
        'id' => 5,
        'type' => 'Grapes',
        'name' => 'Apples 01',
    ),
    4 => array(
        'id' => 6,
        'type' => 'Apples',
        'name' => 'Apples 1',
    ),
    5 => array(
        'id' => 7,
        'type' => 'Grapes',
        'name' => 'Apples 12',
    )
);

uasort($array, function($a, $b) {
    return strcasecmp($a['name'], $b['name']);
});

foreach($array as $single) {
    echo $single['name'].'<br />';
}

Unexpected result from code above:

Apples
Apples 01
Apples 1
Apples 12
Apples 4
Apples 5

The result I wanted to achieve:

Apples
Apples 01
Apples 1
Apples 4
Apples 5
Apples 12

2 Answers 2

7

use strnatcasecmp() for natural ordering

Sign up to request clarification or add additional context in comments.

Comments

0

Your sample array does not indicate the need for case-insensitive comparisons, so strnatcmp() will suffice. Demo

uasort(
    $array,
    fn($a, $b) => strnatcmp($a['name'], $b['name'])
);

If you didn't need to preserve the first level keys, array_multisort() could be used to avoid performing iterated function calls. Demo

array_multisort(
    array_column($array, 'name'),
    SORT_ASC,
    SORT_NATURAL,
    $array
);
var_export($array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.