In this tutorial, we will teach you how to reverse a string in PHP without using string function using a loop in PHP.
Reverse String in PHP
Here are two ways:
- Reverse string in PHP without using string function PHP
- Reserve a string with using string function in PHP
Reverse string in PHP without using string function PHP
Let’s follow the below steps for creating a PHP program to reverse a string without using the function:-
- Declare a PHP variable and assign the string to a variable
- Using the assigned variable, Calculate the length of string
- Declare a variable in which you have stored a reverse string
- iterate the string with for loop
- Concatenate the string inside the for loop
- Print the reversed string
<?php //declare variable and assign a string $str = "Hello"; //count length of string using php count function $count = strlen($str); //Declare a variable in which you have stored a reverse string $revStr = ''; for ($i=($count-1) ; $i >= 0 ; $i--) { // stored a string $revStr .= $str[$i]; } // print $revStr variable, it will return reverse string print_r($revStr); ?>
Source Code – Reverse string without using string function In php
<!DOCTYPE html> <html lang="en"> <head> <title>Reverse string in PHP without using string function PHP </title> </head> <body> <h4>Reverse string in PHP without using string function PHP </h4> <?php //declare variable and assign a string $str = "Hello"; //count length of string using php count function $count = strlen($str); //Declare a variable in which you have stored a reverse string $revStr = ''; for ($i=($count-1) ; $i >= 0 ; $i--) { // stored a string $revStr .= $str[$i]; } // print $revStr variable, it will return reverse string print_r($revStr); ?> </body> </html>
Reserve a string with using string function in PHP
Let’s follow the below steps to create a program to reverse a string using function:
- Declare a PHP variable and assign the string to a variable
- Put a declare variable into inside the strrev() and print it
<?php $str = "Hello World!"; echo "Reverse string of $string is " .strrev( $str ); ?>
Source Code – Reverse a string with using strrev() Function In PHP
<!DOCTYPE html> <html lang="en"> <head> <title>Reverse string in PHP with using strrev() string function PHP </title> </head> <body> <h4>Reverse string in PHP with using strrev() string function PHP </h4> <?php $str = "Hello World!"; echo "Reverse string of $string is " .strrev( $str ); ?> </body> </html>
Conclusion
In this reverse string in PHP tutorial. You have learned how to reverse a string in PHP without using any function In PHP and also learn how to reverse a string using inbuilt PHP function strrev().