views:

133

answers:

3

i have an array like this (after i unset some elements):

$array[3] = 'apple';
$array[5] = 'pear';
$array[23] = 'banana';

which function do i use to sort them to:

$array[0] = 'apple';
$array[1] = 'pear';
$array[2] = 'banana';

i tried some of the sort functions but it didnt work.

+2  A: 

I'm not 100% sure on what your intent is. To simply sort an array based on value but assign new keys, use sort():

sort($array);
print_r($array);

Keys aren't preserved with this particular function. Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => pear
)

But if you want to sort the array by key value use ksort():

ksort($array);
print_r($array);

Output:

Array
(
    [3] => apple
    [5] => pear
    [23] => banana
)

That will preserve the keys however. To reassign keys for an array from 0 onwards use array_values() on the result:

ksort($array);
$array_with_new_keys = array_values($array); // sorted by original key order
print_r($array_with_new_keys);

Output:

Array
(
    [0] => apple
    [1] => pear
    [2] => banana
)
cletus
but that doesnt assign new keys
weng
oh, actually it did=)
weng
That won't preserve the order apple, pear, banana. He wants to order by value, but reset the keys.
Seb
Yes it does. ksort() retains keys. sort() does not.
cletus
Cletus, he doesn't want to sort by value (look: apple, pear, banana). sort() will do: apple, BANANA, pear. Look at my answer.
Seb
+3  A: 

ksort() will sort by key, then get the values with array_values() and that will create a new array with keys from 0 to n-1.

ksort($array)
$array = array_values( $array );

Of course, you don't need ksort if it's already sorted by key. You might as well use array_values() directly.

Seb
+3  A: 
$arrayOne = array('one','two','three'); //You set an array with certain elements
unset($array[1]);                       //You unset one or more elements.
$arrayTwo = array_values($arrayOnw);    //You reindex the array into a new one.

print_r($arrayTwo);                     //Print for prove.

The print_r results are:

Array ( [0] => one [1] => three )
johnnyArt
this was a good solution two
weng
I'm glad it suited you.
johnnyArt