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.

Newsvine | Del.icio.us | Digg
In Web, PHP on March 24th, 2006 | 3 Remarks

3 Remarks to “Sorting Arrays By Length in PHP”

  1. Mike Cherim remarks:

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

  2. HM2K remarks:

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

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

  3. Jona remarks:

    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 Remark

 

Note: HTML is allowed. (<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> ).