Joined March 2012
·

Peter Mitchell

Developer at Freelance
·
Montreal
·
·
·

Posted to [PHP] String Length, The Right Way over 1 year ago

Good job on highlighting the necessity of the mb_* extensions for handling UTF-8 strings. However I disagree with your second assertion, the best way to compare string length in PHP is the obvious way. By making a micro-optimisation such as this early, you lose a communicative aspect to your code.

$str = 'hello!';

if (isset($str[5)) {
    // ... $str is less than or equal to 5
}

if (mb_strlen($str) <= 5) {
    // ... don't need a comment here, the intention is obvious
}

What if I want to check if a string is greater than 6? Then I am back to using mb_strlen.

These cases should only be targeted for optimisation when actually needed, by taking this practice into common use you may lose more than you gain.

Achievements
129 Karma
2,362 Total ProTip Views