Reverse a String in PHP Without Using Built-in Functions
Interview questions often push you to strip away your usual shortcuts and rely on fundamental language mechanics. A common constraint is reversing a string without using strrev() or strlen(). The challenge isn't just about logic; it's about understanding how PHP handles strings at the memory level. If you try to treat a string exactly like an array, you will hit a wall immediately because of how PHP distinguishes between string offsets and array indices.
The source material provided contains a classic attempt that fails with an "Uninitialized string offset: -1" error. This happens because the code tries to access $string[$i] where $i becomes negative. In PHP, when you iterate backwards through a string using integer keys, once the index goes below zero, it attempts to treat the key as a boolean or accesses uninitialized memory relative to the current offset context, triggering that specific warning.
To solve this without strlen(), you must first determine the length of the string manually. You cannot assume a fixed size, nor can you rely on $i-- to naturally stop at zero while accessing valid characters if your loop logic isn't perfect. The most robust way to find the last index is to iterate forward until the offset becomes invalid.
Consider this approach:
$string = "ZEESHAN";
$length = 0;
// Iterate until we hit an invalid offset
while (isset($string[$length])) {
$length++;
}
// $length now holds the number of characters
// We can reverse using a loop starting at $length - 1
for ($i = $length - 1; $i >= 0; $i--) {
echo $string[$i];
}
This logic works because isset($string[$offset]) returns false once the offset exceeds the string's boundaries. In PHP, a string is technically an indexed array where every character has a valid integer key starting from 0. By incrementing $length until isset fails, we capture the total count without ever needing strlen().
However, there is a significant performance trade-off here. Using isset() inside a loop to determine length is functionally equivalent to what strlen() does internally, but it incurs the overhead of PHP's engine checking every single character one by one in a manual loop. In a tight loop running millions of times, this manual iteration is slower than the optimized C-level implementation of strlen(). For an interview or a learning exercise, this distinction demonstrates understanding of memory offsets, but in production code, always prefer strlen() unless you are explicitly forbidden from using it.
Another pitfall in the original example code involves the condition ($string[$i]) != null. In PHP, comparing a string character to null is semantically incorrect. Characters are strings (which evaluate to true), and accessing an invalid offset evaluates to false, not null. Furthermore, relying on boolean conversion for loop conditions can be fragile. The isset() check is the canonical way to detect the end of a string when treating it as an array.
If you need to handle multi-byte encodings like UTF-8, this manual iteration approach becomes even more dangerous. A single character might occupy multiple bytes. Accessing $string[$i] treats the string as a sequence of bytes, not characters. If your string contains emojis or accented characters, reversing byte-by-byte will corrupt the text. For example, an emoji might be stored as four bytes; reversing those bytes individually results in gibberish rather than a reversed string.
While this exercise is excellent for understanding array indexing and loop control structures, it highlights why we rely on built-in functions in real-world applications. If you are working within the Laravel ecosystem, you would typically utilize str() helper methods or stringable objects which handle these edge cases gracefully. You might find relevant discussions on how to manipulate strings safely at https://laravelcompany.com regarding best practices for string handling in modern PHP development.
Ultimately, the goal of such a constraint is not to build a production-ready utility, but to verify that you understand the underlying data structures. By manually incrementing the index until isset() returns false, you prove you know how PHP stores strings as indexed arrays, ensuring you won't accidentally break code when switching between string and array functions.