DraggonZ
DraggonZ

Reputation: 1087

Detecting end of string without using functions

How to find out end of PHP string? I have one task: recognize string length without any functions. I know all strings in PHP ends with null byte (\0), but I can't know elements of string after last symbol.

For example, this will not work:

while($a[++$length]);

How to know length of string without using any functions?

Upvotes: 3

Views: 7306

Answers (2)

phihag
phihag

Reputation: 287745

In php, strings do not end with a null byte. For example, $s = 'a';echo $s[1]; produces a warning (that's why you shouldn't test with $a[$length] == ""). Also, php strings can contain null bytes - they're really byte arrays.

However, you can use the language construct isset to test whether reading the value of $a[$length] would produce a warning:

$a = "a\0b\0c";
for ($length = 0;isset($a[$length]);$length++) ;
echo $length; // 5

Upvotes: 14

Alex Pliutau
Alex Pliutau

Reputation: 21957

$string = 'hello';
$length = 0;
while (isset($string[$length])) {
    $length++;
}
echo $length; //5

Upvotes: 4

Related Questions