Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array starting with given value

Tags:

php

I would like to sort a php array starting with a value I set

Example:

$array = array();
$array['test'] = 'banana';  
$array['test2'] = 'apple';  
$array['test3'] = 'pineapple';  
$array['test4'] = 'orange';  

How do I sort it so that 'orange' is the first result then it sorts alphabetical from then on.

So it would be
orange
apple
banana
pineapple

Any help on this would be greatly appreciated.

like image 893
markc Avatar asked Aug 16 '26 06:08

markc


2 Answers

You can create your own custom sorting function and then use usort (or uasort if you want to preserve your array keys -- thanks to Isaac in the comments for the reminder) to sort your array with it:

function sort_fruit($a, $b)
{
  if ($a == $b) return 0;         // If the values are the same, usort expects 0 
  if ($a == "orange") return -1;  // $a is orange, $b is not -> $a comes first
  if ($b == "orange") return 1;   // $b is orange, $a is not -> $b comes first
  return strcmp($a, $b);          // ... otherwise, sort normally
}

usort($array, "sort_fruit");
like image 186
Daniel Vandersluis Avatar answered Aug 18 '26 18:08

Daniel Vandersluis


This might be a little over the top, but I'm not aware of a single method that will do what you are asking:

<?php

$old_array = array(
    1 => 'banana',
    2 => 'apple',
    3 => 'pineapple',
    4 => 'orange'
);

$search = 'orange';

$new_array = array();

if( ($key = array_search($search, $old_array)) !== FALSE)
{
    $new_array[] = $search;
    unset($old_array[$key]);
}

$new_array = array_merge($new_array, asort($old_array));
like image 37
bschaeffer Avatar answered Aug 18 '26 18:08

bschaeffer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!