How to reverse a string using PHP
In this tutorial, we will learn how to reverse a string using PHP. First, we will create an HTML form for the input string.
HTML Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <head> <title>Reverse a String</title> </head> <body> <table> <form name="reversestring" method="post"> <tr> <td>Enter a String :</td> <td><input type="text" name="string" required></td> </tr> <tr> <td></td> <td><input type="submit" value="Reverse" name="submit" /></td> </tr> </form> </table> </body> </html> |
PHP Logic for reverse a string
1 2 3 4 5 6 7 8 9 10 11 |
<?php if(isset($_POST['submit'])) { $string=$_POST['string']; $length = strlen($string); for ($i=($length-1) ; $i >= 0 ; $i--) { echo $string[$i]; } } ?> |
Here is the full code
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 |
<?php if(isset($_POST['submit'])) { $n=$_POST['num']; function reverse_number($number) { $snum = (string) $number; $revstr = strrev($snum); $reverse = (int) $revstr; return $reverse; } echo reverse_number($n); } ?> <!DOCTYPE html> <html> <head> <title>Reverse a number </title> </head> <body> <table> <form name="reverse" method="post"> <tr> <td>Enter Number :</td> <td><input type="text" name="num" required></td> </tr> <tr> <td></td> <td><input type="submit" value="Reverse" name="submit" /></td> </tr> </form> </table> </body> </html> |