PHP logic to reverse a string

<?php
// Function to reverse a given string
function reverseText($text) {
// Get the length of the input text
$textLength = strlen($text);

// Initialize an empty array to hold characters in reverse order
$revArray = [];

// Loop through each character of the text in reverse order
for ($i = $textLength – 1; $i >= 0; $i–) {
// Add each character to the reverse array starting from the end
$revArray[count($revArray)] = $text[$i];
}

// Combine all elements in revArray into a single string
$reversedText = implode(”, $revArray);

// Return the reversed string
return $reversedText;
}

// Example usage of the reverseText function
$inputText = “abcdef”; // Define the input text
$outputText = reverseText($inputText); // Reverse the input text
echo $outputText; // Output the reversed text of the code:
?>

You can check the explanation of added comments:

  • Function Header: Provides a high-level summary of what the function does.
  • String Length: Explains that we are getting the length of $text.
  • Reverse Array Initialization: Clarifies the purpose of $revArray.
  • Loop: Indicates we’re iterating through $text in reverse.
  • Array to String: Describes that implode is used to create the reversed string.
  • Return Statement: Marks the end of the function, returning the reversed string.
  • Example Usage: Demonstrates how to use the function and print the result.