0

I have an array that I need to re-order. It is an array of country codes:

$countries = array('uk', 'fr', 'es', 'de', 'it');

I need to sort the array with a particular user selected country first, ie. 'fr' and the remaining items need to be in alpabetical order.

I am not too sure how to do this, any help would be appreciated.

0

3 Answers 3

3
$countries = array('uk', 'fr', 'es', 'de', 'it');
// find and remove user value
$uservar = 'uk';
$userkey = array_search($uservar, $countries);
unset($countries[$userkey]);
// sort ascending
sort($countries,SORT_ASC);
// preappend user value
array_unshift($countries, $uservar);
Sign up to request clarification or add additional context in comments.

2 Comments

I don't know for sure, but it will probably save a μs if you first unset the value, then sort it, and then prepend it, because then there is less to sort. :-)
@YMMD your probably right !!!! updated my order !!!! Optimised for performance now
2

This is a bit long, but should work.

<?php
   $user_selected = 'fr';

   $countries = array('uk', 'fr', 'es', 'de', 'it');
   unset($countries[ array_search($user_selected, $countries) ]); // remove user selected from the list
   sort($countries); // sort the rest

   array_unshift($countries, $user_selected); // put the user selected at the beginning

   print_r($countries);
?>

1 Comment

Your "unset" is wrong. $user_selected is the value, not the key. Otherwise, good solution (the algorithm is sane overall).
0
// The option the user selected
$userSelectedOption = 'fr';

// Remove the user selected option from the array
array_splice($countryCodes, array_search($userSelectedOption, $countryCodes), 1);

// Sort the remaining items
sort($countryCodes, SORT_ASC);

// Add the user selected option back to the beginning
array_unshift($countryCodes, $userSelectedOption);

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.