1

I have a simple question: Query returns array in which I would like to change order of elements in PHP.

I have an array like this:

$typesSumAr = array( 'break', 'private absence', 'sick leave', 'vacation', 'work', 'work absence' );

I would like to have an array in this order:

$typesSumAr = array( 'work', 'break', 'sick leave', 'vacation', 'private absence', 'work absence' );

The are not always all elements in array, it could be only two for example, so I cannot hardcode the array. Do I need to make if statements to find out if key exists and then order it manually?

2
  • 1
    What logic should the ordering be based on? Commented Feb 24, 2014 at 11:43
  • No logic, I would like to have it in order of second array. Commented Feb 24, 2014 at 11:45

2 Answers 2

2

Seeing as you have an array in the order you prefer, your problem boils down to keeping the elements that are also present in another array. PHP has a function for exactly that: array_intersect

array_intersect returns an array containing all the values of its first array argument that are present in all the arguments. Note that keys are preserved.

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

Comments

1

There are lots of great array sorting function depending on how you want to sort it. Have a look here http://www.php.net/manual/en/array.sorting.php or even based on your own function via uksort (http://www.php.net/manual/en/function.uksort.php)

1 Comment

Useful, thank you, but I needed array_intersect in this case.

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.