Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP String Functions Complete Reference
Next article icon

PHP Reverse a String

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Reversing a string in PHP refers to rearranging a given string's characters in reverse order, starting from the last character to the first. This task is often used in text manipulation or algorithm challenges, highlighting PHP's string-handling capabilities.

Examples:

Input : GeeksforGeeks
Output : skeeGrofskeeG

Input : 12485
Output : 58421

Below we have discussed about three basic and most commonly used methods of reversing strings in PHP:

Table of Content

  • Reversing string using strrev()
  • Reversing string using recursion and substr()
  • In-place reversing a string without using library functions

Reversing string using strrev()

The strrev() function in PHP provides a straightforward approach to reversing a string. It takes a string as input and returns a new string with the characters in reverse order, making it an efficient tool for text manipulation.

Syntax

strrev($string)

Example :

In this example we defines a Reverse() function that uses strrev() to reverse a given string. The string "GeeksforGeeks" is passed to the function and the reversed result is printed.

PHP
<?php // PHP program to reverse a string using strrev()  function Reverse($str){     return strrev($str); }  // Driver Code $str = "GeeksforGeeks"; echo Reverse($str) ?> 



Output
skeeGrofskeeG

Reversing string using recursion and substr()

Reversing a string using recursion and substr() involves breaking the string into smaller parts. The substr() function extracts the last character, and recursion reverses the remaining string until it reaches the base case of an empty string, then reassembles it in reverse order.

Example: In this example we defines a recursive function Reverse() that reverses a string by slicing the first character and appending it to the reversed substring. The base case returns the string when only one character remains.

PHP
<?php   // PHP function to reverse a string using  // recursion and substr()  function Reverse($str){  	 	// strlen() used to calculate the  	// length of the string  	$len = strlen($str);   	// Base case for recursion  	if($len == 1){  		return $str;  	}  	else{  		$len--;  		 		// extract first character and concatenate  		// at end of string returned from recursive  		// call on remaining string  		return Reverse(substr($str,1, $len))  						. substr($str, 0, 1);  	}  }   // Driver Code  $str = "GeeksforGeeks";  print_r(Reverse($str));   ?>  

Output
skeeGrofskeeG

In-place reversing a string without using library functions:

In-place string reversal modifies the original string without creating a copy. The approach involves swapping characters from both ends, starting with the first and last, and continuing inward until the middle of the string is reached.

Example: This PHP function reverses a string in-place by swapping characters from both ends towards the middle, without using library functions. It iterates over the string, exchanging corresponding characters, and returns the reversed string.

PHP
<?php // PHP function to in place reverse a string  // without using library functions  function Reverse($str){     for($i=strlen($str)-1, $j=0; $j<$i; $i--, $j++)      {         $temp = $str[$i];         $str[$i] = $str[$j];         $str[$j] = $temp;     }     return $str; }  // Driver Code $str = "GeeksforGeeks"; print_r(Reverse($str)); ?> 

Output
skeeGrofskeeG

Next Article
PHP String Functions Complete Reference
author
chinmoy lenka
Improve
Article Tags :
  • Misc
  • Web Technologies
  • PHP
  • Reverse
  • C-String-Question
Practice Tags :
  • Misc
  • Reverse

Similar Reads

  • How to replace String in PHP ?
    Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each
    3 min read
  • PHP | Serializing Data
    Most often we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array. But, we already have a handy solution to handle t
    3 min read
  • PHP String Functions Complete Reference
    Strings are a collection of characters. For example, 'G' is the character and 'GeeksforGeeks' is the string. Installation: These functions are not required any installation. These are the part of PHP core. The complete list of PHP string functions are given below: Example: This program helps us to c
    6 min read
  • Remove new lines from string in PHP
    Given a multiple line sentence or statement the task is to convert the whole statement in a single line. See the example below. Examples: Input : Hello welcome to geeksforgeeks.Output : Hello welcome to geeksforgeeks.Remove the new line between Hello and geeksforgeeks.Input : I love geeksforgeeksOut
    2 min read
  • PHP | strtr() for replacing substrings
    It replaces given substring in a string with another given string. We can also use it to do multiple replacements by passing an array of pairs. Examples: Input : $str = "Hmrrb GmmksfbrGmmks"; $from = "rbm"; $to = "loe"; Output : Hello GeeksforGeeks Input : $str = "Hello world"; $arr = array("Hello"
    2 min read
  • PHP | simplexml_load_string() Function
    Sometimes there is a need of parsing XML data in PHP. There are a handful of methods available to parse XML data. SimpleXML is one of them. Parsing an XML document means that navigating through the XML document and return the relevant pieces of information. Nowadays, a few APIs return data in JSON f
    3 min read
  • PHP String Functions
    Strings are a fundamental data type in PHP, used to store and manipulate text. PHP provides a wide variety of built-in string functions. These functions perform various operations such as string transformations, character manipulations, encoding and decoding, and formatting, making string handling s
    6 min read
  • PHP str_replace() Function
    In this article, we will see how to replace the occurrence of the search string with the replacing string using the str_replace() function in PHP, along with understanding their implementation through the examples. The str_replace() is a built-in function in PHP and is used to replace all the occurr
    3 min read
  • Explain some string functions of PHP
    In the programming world, a string is considered a data type, which in general is a sequence of multiple characters that can contain whitespaces, numbers, characters, and special symbols. For example, "Hello World!", "ID-34#90" etc. PHP also allows single quotes(' ') for defining a string. Every pro
    7 min read
  • PHP str_pad to print string patterns
    str_pad: Pad a string to a certain length with another string. Syntax:- str_pad (input, pad_length, pad_string_value, pad_type) It returns the padded string. Parameters Description input:-The input string. pad_length:-If the value of pad_length is negative, less than, or equal to the length of the i
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences