Home » PHP » PHP Examples

PHP | Reverse a given string without using the library function

Reversing a string in PHP: Here, we are going to learn how to reverse a given string in PHP without using the library function.
Submitted by Bhanu Sharma, on August 11, 2019

Given a string and we have to reverse it without using a library function.

Example:

    Input: "Hello world!"
    Output: "!dlrow olleH"

    Input: "Welcome @ IncludeHelp.Com"
    Output: "moC.pleHedulcnI @ emocleW"

PHP code to reverse the string without using library function

<?php
//PHP code to reverse the string without 
//using library function

//function definition 
//it accepts a string and returns the revrse string
function reverse_string($text){
    $rev = ''; //variable to store reverse string
    $i = 0; //counting length
    
    //calculating the length of the string 
    while(isset($text[$i])){
        $i++;
    }
    
    //accessing the element from the reverse
    //and, assigning them to the $rev variable 
    for($j = $i - 1; $j >= 0; $j--){
        $rev .= $text[$j];
    }    
    
    //returninig the reversed string
    return $rev;
}

//main code i.e. function calling
$str = "Hello world!";
$r_str = reverse_string($str);
echo "string is: ". $str . "<br/>";
echo "reversed string is: ". $r_str . "<br/>";

$str = "Welcome @ IncludeHelp.Com";
$r_str = reverse_string($str);
echo "string is: ". $str . "<br/>";
echo "reversed string is: ". $r_str . "<br/>";

?>

Output

string is: Hello world!
reversed string is: !dlrow olleH
string is: Welcome @ IncludeHelp.Com
reversed string is: moC.pleHedulcnI @ emocleW

Explanation:

Since we can't use the library function, In the function - we run a for loop to reverse the strings by storing the sequence in reverse order in the variable $rev. An additional while loop is set up to check if the variable $text contains a valid string (i.e. to calculate the length). This is an additional safety check to ensure that the program works even if numbers are put into the function.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.