Sort an array and assign new numeric keys?

I have an array like this (after I disabled some elements):

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

What function do I use to sort them by:

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

I tried some of the sort functions, but it did not work.

+6
sorting arrays php
source share
3 answers

I am not 100% sure about your intentions. To simply sort the array based on the value, but assign new keys, use sort() :

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

Keys are not stored with this particular function. Exit:

 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 ) 

This will save the keys. To reassign keys to an array with 0, use array_values() as a 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 ) 
+15
source share

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

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

Of course, you do not need ksort if it is already sorted by key. You can also use array_values ​​() directly.

+6
source share
 $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. 

print_r results:

 Array ( [0] => one [1] => three ) 
+4
source share

All Articles