There's a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is "super slow". Well, that was probably true in old versions of PHP. But as of PHP7 that's definitely no longer true. It's now SUPER fast!
I created a 20,00,000 byte string (~20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.
The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn't get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation
So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!
Here is the complete benchmark code if you want to reproduce it on your machine:
<?php
$iterations = 100000000; // 100 million
$str = str_repeat( '0', 20000000 );
// benchmark loop and variable assignment to calculate loop overhead
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i ) {
$len = 0;
}
$end = microtime(true);
$loop_elapsed = 1000 * ($end - $start);
// benchmark strlen in a loop
$len = 0;
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i ) {
$len = strlen( $str );
}
$end = microtime(true);
$strlen_elapsed = 1000 * ($end - $start);
// subtract loop overhead from strlen() speed calculation
$strlen_elapsed -= $loop_elapsed;
echo "\nstring length: {$len}\ntest took: {$strlen_elapsed} milliseconds\n";
?>