Reverse a String
Write a PHP function that reverses a given string manually without using the built-in strrev() function.
Use strlen() to get the string length. Loop from the last character index (length - 1) down to 0. Access each character with bracket notation $text[$i] and append it to a result string using the .= concatenation assignment operator.
PHP strings are byte sequences that can be accessed as arrays with integer indices. The .= operator efficiently builds strings without creating intermediate copies.
Edge cases include empty strings (return empty), single character strings (the loop runs once), and strings with spaces and special characters.
The time complexity is O(n) and space complexity is O(n) for the result string.
String reversal is a fundamental operation in programming. The backward loop approach demonstrates manual string manipulation without relying on built-in functions. PHP's string indexing with brackets treats the string as an array of bytes.
The .= operator in PHP appends strings efficiently. Starting from an empty string and building up by prepending each character from the original string in reverse order produces the reversed result.Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that reverses a given string manually without using the built-in strrev() function.
Use strlen() to get the string length. Loop from the last character index (length - 1) down to 0. Access each character with bracket notation $text[$i] and append it to a result string using the .= concatenation assignment operator.
PHP strings are byte sequences that can be accessed as arrays with integer indices. The .= operator efficiently builds strings without creating intermediate copies.
Edge cases include empty strings (return empty), single character strings (the loop runs once), and strings with spaces and special characters.
The time complexity is O(n) and space complexity is O(n) for the result string.
Best Answers
<?php
function reverseString($text) {
$r='';for($i=strlen($text)-1;$i>=0;$i--){$r.=$text[$i];}return $r;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
