Reversing a string in PHP is completely simple to use inbuild function “strrev()”. However often you may consider the task of reversing a string in PHP without using the “strrev()” function in PHP interview. You can reverse string without using any function in PHP easily.
The following are the steps:
Logic:
- Take three variables first for a string which you have to convert “$string”, the second variable will be stored the reverse string “$reverce” and third will interact each character of the string $i
- Check the empty string in while loop
- Concatenate the string inside the while loop and store the the value like “$reverse = $string[$i].$reverse;”
- Print or display the reversed($reverse) string out site the while loop.
Let’s take an example to understand:
1 2 3 4 5 6 7 8 9 10 | <?php $string = 'john'; $reverse = ''; $i = 0; while(!empty($string[$i])){ $reverse = $string[$i].$reverse; $i++; } echo $reverse; ?> |
Output: The above code did reverse the string to ‘nhoj’.
1 | nhoj |
Reverse String Without Using Any Function using HTML Form:
You can follow the steps to use this code:
- Copy the below-mentioned code.
- Create a file into your webserver and paste the copied code.
- Open the created file on the browser.
- There will be shown an input box.
- Enter your string and click on the “Submit” button.
- After clicking the button, there will be shown output above the text box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <!DOCTYPE html> <html> <head> <title>Reverse a string without using any php function</title> </head> <body> <?php if(isset($_GET['submit'])){ $string = $_GET['string']; $reverse = ''; $i = 0; while(!empty($string[$i])){ $reverse = $string[$i].$reverse; $i++; } echo $reverse; } ?> <form action="" method="get"> <input type="text" name="string" placeholder="Enter String" required><br><br> <input type="Submit" value="Submit" name="submit"> </form> </body> </html> |
You can check the YouTube video of “Reverse String Without Using Any Function in PHP”.