PHP Program to find the reverse of the string

What is the reverse of a number?

In this program, we are reversing the string using PHP. Reversing the string is meant by printing the user inputted string in reverse order. For example, if the user entered string is windows then the output of the program will be swodniw.

How to find the reverse of a string in PHP?

It is quite simple and there are many ways to find the reverse of a string using PHP. The easiest way is to use the built-in function strrev() which directly returns the reverse of the entered string. But in this program, we are finding the reverse of the string without using the function. Here we first read the input from the user and assigns it to the variable char after that we find the length of the string using the built-in function strlen() and assigns the value into the variable len. Then we assign the value of 'len - 1' into the variable i and perform the for loop until the condition 'i >= 0' becomes false and we will also decrement the value of the variable in every iteration and print the value of the variable char with the index of the value of variable i. By performing these steps we can find the reverse of the string.

ALGORITHM

Step 1: Read the input from the user for which we want the reverse into variable char

Step 2: Find the length of the variable char using the built-in function strlen() and assign it to the variable len

Step 3: Assign the computed value of 'len - 1' into the variable i and perform step 4 until the condition 'i >= 0' becomes false and decrement the value of variable i in every iteration

Step 4: Print the value of variable char with the index of the value of variable i

PHP Source Code

                                          <?php
$char = readline("Enter the string: ");
$len = strlen($char);
echo "Reverse of $char is ";
for ($i = ($len - 1); $i >= 0; $i--) {
    echo $char[$i];
}
?>
                                      

OUTPUT

Enter the string: algorithm
Reverse of algorithm is mhtirogla