Simple PHP programs Part II
Simple PHP programs part II
Before going to this, if you missed the Simple PHP programs part I. Click below this link to to visit Part I: Simple PHP programs
Simple PHP programs Part I
1. To find the factorial value of the given number
<html>
<head>
<title>Factorial Value for the given value</title>
</head>
<body>
<center>
<form method="post">
<tr>
<td><b>Enter the number : </b></td>
<td><input type="number" name="number"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
<?php
$n=$_POST['number'];
$i=1;$f=1;
while($i<=$n)
{
$f=$f*$i;
$i++;
}
echo "The factorial value for the given number is <b style='font-size:22px;color:green'>$f</b>";
?>
</center>
</body>
</html>
Output:
For the above example, I have used "while" loop. We can also use do...while and for loop also. HTML code will read the data, which inserted by the user. According to the data, php program will do some actions based on the coding that we given. The while loop will execute again and again when the condition become false.
2. To add individual values of the given 4-digit number again and again when it comes as a single value
<html>
<head>
<title>Adding individual digits in given number</title>
</head>
<body>
<center>
<form method="post">
<tr>
<td><b>Enter the 4-digit number : </b></td>
<td><input type="number" name="number"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
<?php
$n=$_POST['number'];
function digits($x)
{
if($x == 0)
return 0;
else
return ($x%10 + digits($x/10));
}
$s=digits($n);
$result=digits($s);
echo "Sum of individual digits of given 4-digit number is <b style='color:green;font-size:28px'> $result</b>";
?>
</center>
</body>
</html>
Output:
I have used "recursive function" for this program. We can also use "for" loop to do this operation. It add all individual numbers in given number. For example, 4521 had given by the user. Add all this individual numbers. "4 + 5 + 2 + 1 = 12". We got 2 digit value from the 4 digit number. Again add that 12. "1 + 2 = 3" is the output. If you use "for" loop, you need to give 2 for loops, or you can "goto" statement nearer to the for loop. So, it will increase code length. I used function to do this operation.
3. To check whether the given word is Palindrome or not
<html>
<head>
<title>To check whether the given string is Palindrome or not</title>
</head>
<body>
<center>
<form method="get">
<tr>
<td><b>Enter a string : </b></td>
<td><input type="text" name="name"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</form>
<?php
$n=$_GET['name'];
$r=strrev($n);
if(strcmp($n,$r)==0)
echo "The given string is <b style='color: green; font-size: 20px;'>Palindrome</b>";
else
echo "The given string is <b style='color: red; font-size: 20px;'>not a Palindrome</b>";
?>
</center>
</body>
</html>
Comments
Post a Comment