How can I detect the end of a string in PHP without using built-in functions?

Solution:

In PHP, strings do not automatically end with a null byte, and they can contain null bytes internally. For example:


$s = 'a';
echo $s[1]; // Produces a warning

Because of this, you should not test the end of a string with $a[$length] == “”.

Instead, you can use isset() to safely determine the string length without warnings:


$a = "a\0b\0c"; // String containing null bytes

for ($length = 0; isset($a[$length]); $length++);

echo $length; // Output: 5

✅ Explanation:

isset($a[$length]) returns false when the index is out of bounds.

This approach correctly counts all bytes, including null bytes, without triggering warnings.