0

How do I create a PHP function that will order/sort an array by desired order, based on its key?

The array will contain string or numeric value, for example I have:

array = A,B,C,D,E,F

I would like to change the array based on its key so create

create_array_index(5,2,4,1,3,0) will show array F,C,E,B,D,A create_array_index(0,2,4,1,3,5) will show array A,C,E,B,D,F

I know, I can access the value manually ex : $array[5],$array[2],... and so on, but it will take a lot of time. Is there any function for this?

1

4 Answers 4

1

Function ksort() is the best while you use the sorting by key.

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

1 Comment

you can use krsort() for reverse order sorting by key
1

There are few ways using some php sort functions (like other guys already sugessted), this is another short way how to do this job.

function sortArrayByKeys()

function sortArrayByKey($keystring, $origarray) {
  $res = array();
  $keys = explode(',', $keystring);
  foreach ($keys as $key) $res[] = $origarray[$key];
  return $res;
  }

test:

$original_array = array('A', 'B', 'C', 'D', 'E', 'F');

$sort_pattern = '5,2,4,1,3,0';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array) . "<br />\n";

$sort_pattern = '0,2,4,1,3,5';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array) . "<br />\n";

$sort_pattern = '5,4,3,2,1,0';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array) . "<br />\n";

$sort_pattern = '0,5,4,2,1,3';
$new_array = sortArrayByKey($sort_pattern, $original_array);
echo "$sort_pattern => " . join(',', $new_array);

output:

5,2,4,1,3,0 => F,C,E,B,D,A
0,2,4,1,3,5 => A,C,E,B,D,F
5,4,3,2,1,0 => F,E,D,C,B,A
0,5,4,2,1,3 => A,F,E,C,B,D

Cheers ;)

1 Comment

I've been looking for best way to do the same. Your answer is probably simplest.
0

Check the different sort options available in PHP.

Sort based on array keys - https://www.php.net/ksort

You can also sort based on your own comparison function - https://www.php.net/manual/en/function.uksort.php

Comments

0

There Are a number of array functions in Php and They are all discussed on PHP Official websites. As for I understand you are looking for ksort (Sort Array By keys) and krsort (Sort Array By Keys In Reverse). Please Check them on the given links. And try it yourself.. Goodluck

You can also create your own custom function to do the required job and use it anytime within your application if you feel ksort and krsort are not flexible or accurate to your requirement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.