Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array sort keys numerically help

Tags:

php

$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 ) 
like image 350
user892134 Avatar asked Dec 12 '22 09:12

user892134


1 Answers

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

like image 97
Chris Baker Avatar answered Jan 03 '23 17:01

Chris Baker