Code Logo

Reverse a String

Published at24 Jul 2026
PHP String Handling Easy 0 views
Like0

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

Example 1
Input
""
Output
""
Example 2
Input
"racecar"
Output
"racecar"
Example 3
Input
"PHP"
Output
"PHP"
Example 4
Input
"Hello"
Output
"olleH"
Example 5
Input
"a"
Output
"a"

Algorithm Flow

Recommendation Algorithm Flow for Reverse a String
Recommendation Algorithm Flow for Reverse a String

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 - Approach 1
<?php
function reverseString($text) {
    $r='';for($i=strlen($text)-1;$i>=0;$i--){$r.=$text[$i];}return $r;
}