Sorting Arrays By Length in PHP

However, in the order given, the color names near the beginning of the array were shorter than the ones near the end of the array; for example, “green” came before “darkgreen.” As a result, after replacement occurred, “darkgreen” became “dark#4b4b4b” (by replacing only the “green” part with a hex equivalent, instead of the entire “darkgreen” part) instead of the darkgreen hex equivalent. Obviously this was unacceptable, so the easiest way to fix the problem was to sort the array in such a way that the shorter names occurred last. Fortunately, PHP allows you to create custom algorithms for sorting arrays, and that’s just what I’ve done.

  1. function sortByLength($a,$b){
  2. if($a == $b) return 0;
  3. return (strlen($a) > strlen($b) ? -1 : 1);
  4. }

Simple, yes, but effective.

Update: This code (written when I was more of a PHP novice) is erroneous. The following function is ideal. As mentioned in the comments, call this function using the PHP usort() (or similar callback) function.

  1. function sortByLength($a,$b){
  2. return (strlen($a) - strlen($b));
  3. }

March 24th, 2006 | 3 Remarks

Comments

  1. Mike Cherim Comments:

    That is simple. Or at least it is now that you’ve solved the problem ;-)

  2. HM2K Comments:

    You didn’t mention that this was to be used in conjunction with usort…

    ie: usort($array,”sortByLength”);

  3. Jona Comments:

    HM2K, thanks for bringing that up. I actually sort of made the assumption that anyone wanting to use a callback function to sort an array would know to use usort, uasort, or uksort to do so.

Leave a Comment