0

I have this associative array that I want to sort in a custom order (not just alphabetically):

$arr = [
    '1' => 'Lorem Ipsum 1',
    '2' => 'Lorem Ipsum 3',
    '3' => 'Lorem Ipsum 2',
    '4' => 'Text A',
    '5' => 'Text B',
    '6' => 'Text C',
    '7' => 'Lorem Ipsum 4',
    '8' => 'Text D',
    '9' => 'Text E',
];

I need this output:

$arr = [
    '4' => 'Text A',
    '5' => 'Text B',
    '6' => 'Text C',
    '8' => 'Text D',
    '9' => 'Text E',
    '1' => 'Lorem Ipsum 1',
    '3' => 'Lorem Ipsum 2',
    '2' => 'Lorem Ipsum 3',
    '7' => 'Lorem Ipsum 4'
];

How the array needs to be sorted (keep key-value association)

  • Sort Array Alphabetically
  • After this, all values that start with Text have to be on top

I already tried it with the function uasort, but could not find out how to sort them starting with Text.

Thank you

3 Answers 3

3

You can use uasort(), and in the sort function, check if the value starts by "Text". If so, sort using this case, otherwise, sort naturally:

$arr = [
    '1' => 'Lorem Ipsum 1',
    '2' => 'Lorem Ipsum 3',
    '3' => 'Lorem Ipsum 2',
    '4' => 'Text A',
    '5' => 'Text B',
    '6' => 'Text C',
    '7' => 'Lorem Ipsum 4',
    '8' => 'Text D',
    '9' => 'Text E',
];
uasort($arr, function($a, $b){
    $a_text = strpos($a, 'Text') === 0;
    $b_text = strpos($b, 'Text') === 0;
    if ($a_text != $b_text) {
        return $b_text - $a_text ;
    }
    return strnatcmp($a,$b);
});
print_r($arr);

Output:

Array
(
    [4] => Text A
    [5] => Text B
    [6] => Text C
    [8] => Text D
    [9] => Text E
    [1] => Lorem Ipsum 1
    [3] => Lorem Ipsum 2
    [2] => Lorem Ipsum 3
    [7] => Lorem Ipsum 4
)
Sign up to request clarification or add additional context in comments.

Comments

1

use asort. http://php.net/manual/en/function.asort.php.

 asort($arr);

asort() - Maintains key association: yes.

2 Comments

The output of your code will create an array starting from Lorem Ipsum 1 and finishing in Text E
And how can I get all the values starting with Text to the top? Just sorting alphabetically does not guarantee this.
0
$arr = [
        '1' => 'Lorem Ipsum 1',
        '2' => 'Lorem Ipsum 3',
        '3' => 'Lorem Ipsum 2',
        '4' => 'Text A',
        '5' => 'Text B',
        '6' => 'Text C',
        '7' => 'Lorem Ipsum 4',
        '8' => 'Text D',
        '9' => 'Text E',
    ];

    rsort($arr);
    var_dump($arr);

1 Comment

And how can I get all the values starting with Text to the top? Just sorting alphabetically does not guarantee this.

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.