EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Reverse String in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Reverse String in PHP

reverse string in php

Introduction to Reverse String in PHP

In this article, we will learn about Reverse String in PHP. A string is the collection of characters that are called from the backside. These collections of characters can be used to reverse either the PHP function strrev() or by using the simple PHP programming code. For example on reversing PAVANKUMAR will become RAMUKNAVAP

Logic:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • At first, assigning the string to the variable.
  • Now calculate the string length.
  • Now create a new variable in order to store the reversed string.
  • Then Proceed with the loop like for loop, while loop and do while loop etc..
  • Concatenating the string inside of the loop.
  • Then display/print the reversed string which is stored in the new variable which is created in the middle.

Reverse String in PHP Using Various Loops

Various Loops like FOR LOOP, WHILE LOOP, DO WHILE LOOP, RECURSIVE METHOD, etc.. in order to Reverse the String in the PHP Programming Language.

 1.Using strrev() function

  • The below example/syntax will reverse the original string using already predefined function strrev() in order to reverse the string. In the example, a $string1 variable is created in order to store the string I mean the original string then the echo statement is used in order to print the original string and the reversed string with the help of strtev() function and then print by concatenating both.
  • You can check the output of the program below to check whether the string is reversed or not.

Code:

<?php
$string1 = "PAVANKUMAR";
echo "Reversed string of the $string1 is " .strrev ( $string1 );
?>

Output:

Reverse String in PHP - 1

2. Using For Loop

  • In the below example, the “$string1” variable is created by assigning the string1 variable’s value as “PAVANSAKE”. Then the $length variable is created in order to store the length of the $string1 variable using the strlen() function. Now the for loop is used with initialization, condition and incrementation values as “$length1-1”, “$i1>=0”, “$i1 – -”. Then the $string1 variable’s index values are calling from the backside using the initialization of $i1 equals to $length-1.
  • At first, FOR LOOP will start with the value of the length of the “original string – 1” value. Then the loop starts running by checking the condition “i1>=0” then the original string’s index is called backward likewise loop will print each index value from the back for each iteration until the condition is FALSE. At last, we will get the Reverse of the string using FOR loop.

Code:

<?php
$string1 = "PAVANSAKE";
$length1 = strlen($string1);
for ($i1=($length1-1) ; $i1 >= 0 ; $i1--)
{
echo $string1[$i1];
}
?>

Output:

Reverse String in PHP - 2

3. Reverse String in PHP using While Loop

  • Here in the below example while loops used in order to print the string which is reversed using the original string “PAVANSAKEkumar”.
  • In the below syntax/php program, at first, a $string1 variable is assigned with string value “PAVANSAKEkumar” then we calculate the length of the $string1 variable’s value and stored in the $length1 variable. It will be an integer always. Now the $i1 variable is the length of the string variable’s value -1($length1-1).
  • Now we start with the WHILE loop here using the condition “$i1>=0” then after that we will print the string’s index value from the back because the $i1 value is the last of the index value of the original string. After this, decrementing will be done in order to reverse the original string($i1=$i1-1).

Code:

<?php
$string1 = "PAVANSAKEkumar";
$length1 = strlen($string1);
$i1=$length1-1;
while($i1>=0){
echo $string1[$i1];
$i1=$i1-1;
}
?>

Output:

Reverse String in PHP - 3

4. Using do while Loop

  • The program of reversing the string in PHP using the DO while loop is listed below. In the below example just like the WHILE LOOP. Every Logic term is the same as the WHILE LOOP but does follow is a bit different it will print the output first rather than checking the condition at first.
  • So even though if you print an output even if the condition result is FALSE.

Code:

<?php
$string1 = "PAVANSAKEkumaran";
$length1 = strlen($string1);
$i1=$length1-1;
do{
echo $string1[$i1];
$i1=$i1-1;
}
while($i1>=0)
?>

Output:

Reverse String in PHP - 4

5. Using the Recursion Technique and the substr()

  • Here in the below example reversing the string is done using the recursion technique and the substr() function. Substr() function will help in getting the original string’s substring. Here a new function called Reverse() also defined which is passed as an argument with the string.
  • At each and every recursive call, substr() method is used in order to extract the argument’s string of the first character and it is called as Reverse () function again just bypassing the argument’s remaining part and then the first character concatenated at the string’s end from the current call. Check the below to know more.
  • The reverse () function is created to reverse a string using some code in it with the recursion technique. $len1 is created to store the length of the string specified. Then if the length of the variable equals to 1 i.e. one letter then it will return the same.
  • If the string is not one letter then the else condition works by calling the letters from behind one by one using “length – -“ and also calling the function back in order to make a recursive loop using the function (calling the function in function using the library function of PHP). $str1 variable is storing the original string as a variable. Now printing the function result which is the reverse of the string.

Code:

<?php
function Reverse($str1){
$len1 = strlen($str1);
if($len1 == 1){
return $str1;
}
else{
$len1--;
return Reverse(substr($str1,1, $len1))
. substr($str1, 0, 1);
}
}
$str1 = "PavanKumarSake";
print_r(Reverse($str1));
?>>

Output:

recursion technique and the substr()

6. Reversing String without using any library functions of PHP

  • The below syntax/ program example is done by swapping the index’s characters using the for loop like first character’s index is replaced by the last character’s index then the second character is replaced by the second from the last and so on until we reach the middle index of the string.
  • The below example is done without using any of the library functions. Here in the below example, $i2 variable is assigned with the length of the original string-1 and $j2 value is stored with value as “0” then in the loop will continue by swapping the indexes by checking the condition “$j2<i2” which means at the middle of the strings index the loop will stop working. At last, we will get the string which is reversed and perfect as we want.

Code:

<?php
function Reverse($str2){
for($i2=strlen($str2)-1, $j2=0; $j2<$i2; $i2--, $j2++)
{
$temp2 = $str2[$i2];
$str2[$i2] = $str2[$j2];
$str2[$j2] = $temp2;
}
return $str2;
}
$str2 = "PAVANKUMARSAKE";
print_r(Reverse($str2));
?>

Output:

library functions of PHP

Conclusion

I hope you understood the concept of logic of reversing the input string and how to reverse a string using various techniques using an example for each one with an explanation.

Recommended Articles

This is a guide to Reverse String in PHP. Here we discuss the logic of reversing the input string and how to reverse a string using various loops with respective examples. You can also go through our other related articles to learn more –

  1. Date Function in PHP
  2. Reverse String in JavaScript
  3. Reverse String in C++
  4. Reverse String in C#

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More