0

I have an array similar in design to the following:

Array
(
    [0] => apple
    [1] => Pear
    [2] => orange
    [3] => mango
    [4] => [banana]
    [5] => Cantaloupe
    [6] => Peach
)

I need to have it sorted so it will output more like:

Array
(
    [4] => [banana]
    [0] => apple
    [5] => Cantaloupe
    [3] => mango
    [2] => orange
    [6] => Peach
    [1] => Pear
)

Meaning I need results in [] listed first, and the rest sorted alphabetically not case sensitive.

I tried natcasesort but that seems to have issues with [].

How exactly would I get the results I am looking for keeping in mind this is an example array and results starting with [ are not always the 4th result nor is the result name actually [banana]

Bruce
  • 1,039
  • 1
  • 9
  • 31

1 Answers1

1

One way to do it with this way- Find out the array index that has brackets [] in it, store that value at position 0 and reset the array index. Then sort remaining part with natcasesort() and merge it with initial array to get the final array.

<?php
$array =Array
(
    '0' => 'apple',
    '1' => 'Pear',
    '2' => 'orange',
    '3' => 'mango',
    '4' => '[banana]',
    '5' => 'Cantaloupe',
    '6' => 'Peach',
);
$value_w_bracket = key(preg_grep('/\[\w+\]/i', $array));
$intermediate[0] = $array[$value_w_bracket];
unset($array[$value_w_bracket]);
natcasesort($array);
$final = array_merge($intermediate,$array);
print_r($final);
?>

WORKING DEMO: https://3v4l.org/KodUI

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103