String is probably the most used data type in PHP as it is a templating language in nature. PHP string counts for a big part of your coding. Not to mention most of us use PHP to do what it does the best – serving web pages, involving a lot of strings all the way.
Okay, let’s cut the bullshit. To get or count the length of a php string, you need the strlen() function.
<?php
$str = 'Hi.';
$length = strlen($str); // $length equals to 3 as there are 3 characters in the string 'Hi.'
?>
A slightly better approach, is to examine the existence of the nth character of a string to determine the length of a string:
if (isset($str[5])) { // $str[5] is the 6th character of $str
echo 'This string is at least 6 bytes in size (6 characters long).';
}
The reasoning of this is that strlen is a function while isset is a language construct which should come faster. Not to mention that intuitively, counting the length of a string from the first byte to the last takes intrinsically more time than the determination of the existence of just one byte.
