Robson » Little Red Book » Sort

Chapter 6 - Question 14

Given an array of values, sort them into non-descending alphabetic or numeric order, as appropriate.

Solution 1

The PHP sort function makes this a very simple problem.

<?
   // randomly select an array of numbers or text
   if (mt_rand(0, 1))
       // array of text
       $values = array('winter', 'autumn', 'spring', 'summer');
   else
       // array of numbers
       $values = array(9, 4, 7, 7, 1, 5);
   
   // show the current array
   echo 'Before: ' . implode(', ', $values);
   
   // sort them non-descending (ascending)
   sort($values);
   
   // output the array
   echo '<br/>After: ' . implode(', ', $values);
   
   // another way of sorting is by natural order,
   // which is useful for things like filenames.
   // for example, pic40.gif will appear *before* pic200.gif with a natural sort
   $files = array('pic78.gif', 'pic200.gif', 'pic40.gif', 'pic111.gif', 'pic7.gif');
 
   // show the current array
   echo '<br/> <br/>Before: ' . implode(', ', $files);
   
   // sort them into natural order
   natsort($files);
   
   // output the array
   echo '<br/>After: ' . implode(', ', $files);
?>

Which produces:

Before: 9, 4, 7, 7, 1, 5
After: 1, 4, 5, 7, 7, 9

Before: pic78.gif, pic200.gif, pic40.gif, pic111.gif, pic7.gif
After: pic7.gif, pic40.gif, pic78.gif, pic111.gif, pic200.gif

Log

© 2004-17 robson | cc unless stated