4
$test1[2] = "one";

$test2[1] = "two";
$test2[3] = "three";

$test = $test1 + $test2;

print_r($test);

I've used the array union operator but when i print the array it is in the wrong order.

Array ( [2] => one [1] => two [3] => three ) 

How do i sort the keys numerically in the array?; so i get the below result.

Array ( [1] => two [2] => one [3] => three ) 
1
  • 1
    By the by... did you try to research this on php.net? us.php.net/… Commented Sep 19, 2011 at 19:24

3 Answers 3

5

There are a number of options, depending on the outcome you're after. Simplest is ksort:

$test1[2] = "one";

$test2[1] = "two";
$test2[3] = "three";

$test = $test1 + $test2;
ksort($test);
print_r($test);

See the docs: http://www.php.net/manual/de/function.ksort.php

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

Comments

5

Try ksort: http://php.net/manual/en/function.ksort.php

print_r($test);
ksort($test);  // (sorts in place)
print_r($test);

Comments

3

How do i sort the keys numerically in the array?

ksort()


Please, please, please take the time to look through the wealth of documentation (not just on array sorting functions), on php.net, before asking here. You'll more often than not find that we've not only documented the functions and what they do, but given you nice examples to demonstrate the usage and even make note of quirks, intricacies and special considerations.

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.