phparrayssorting

Change position of elements in array based on a predefined order


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?


Solution

  • 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.