ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

PHP String Reversal

PHP

Goal -- WPM

Ready
Exercise Algorithm Area
1<?php
2
3function reverseString(string $input):
4string
5{
6$length = strlen($input);
7
8if ($length === 0) {
9return "";
10}
11
12$reversed = "";
13for ($i = $length - 1; $i >= 0; $i--) {
14$reversed .= $input[$i];
15}
16
17return $reversed;
18}
19
20function processStrings(array $strings):
21array
22{
23$results = [];
24foreach ($strings as $str) {
25$results[] = reverseString($str);
26}
27return $results;
28}
29
30?>
Algorithm description viewbox

PHP String Reversal

Algorithm description:

This PHP code defines a function to reverse a given string. It iterates through the string from the last character to the first, appending each character to a new string. This is a fundamental string manipulation task with applications in data processing and text manipulation.

Algorithm explanation:

The `reverseString` function takes a string and returns its reversed version. It first checks for an empty string, returning an empty string if found. Otherwise, it initializes an empty string `$reversed`. A `for` loop iterates from the last index (`$length - 1`) down to 0. In each iteration, the character at the current index `$i` from the input string is appended to `$reversed`. The time complexity is O(n), where n is the length of the string, because each character is processed once. The space complexity is also O(n) due to the creation of the new reversed string. The `processStrings` helper function demonstrates how to apply this reversal to an array of strings.

Pseudocode:

function reverseString(input_string):
  if input_string is empty:
    return ""
  reversed_string = ""
  for i from length(input_string) - 1 down to 0:
    reversed_string = reversed_string + input_string[i]
  return reversed_string