PHP Reverse a given string without using the library function

Turning around a string in PHP: Here, we will figure out how to switch a given string in PHP without utilizing the library function.

Given a string and we need to turn around it without utilizing a library function.



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

    Input: "Welcome @ JustTechReview.Com"
    Output: "ceh Jm ul@sWtcwemoveC.eRoeiT"

PHP code to switch the string without utilizing library function:

//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 
    //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 @ JustTechReview.Com";
$r_str = reverse_string($str);
echo "string is: ". $str . "<br/>";
echo "reversed string is: ". $r_str . "<br/>";



string is: Hello world!
reversed string is: !dlrow olleH
string is: Welcome @ JustTechReview.Com
reversed string is: ceh Jm ul@sWtcwemoveC.eRoeiT


Since we can’t utilize the library function, In the function – we run a for circle to turn around the strings by putting away the arrangement in switch request in the variable $rev. An extra while circle is set up to check if the variable $text contains a legitimate string (for example to compute the length). This is an extra wellbeing check to guarantee that the program works regardless of whether numbers are placed into the function.

Leave a Comment

error: Alert: Content is protected!!