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
<!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
<?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
<?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>
