INTRODUCTION
Get ready to learn how to use arithmetic operators and some numbers to create a simple calculator! In this tutorial, we'll take a journey into the world of PHP programming and build a simple calculator from scratch. Whether you're a math wizard or a coding newbie, this project is a great way to learn the basics of PHP and have some fun along the way. So, grab your calculator (or not, because we'll be building one!) and let's dive in.
CODE SAMPLE
<?php
$number_1=56;
$operator="+";
$number_2=6;
if($operator=="+"){
$answer=$number_1 + $number_2;
}else if($operator=="-"){
$answer=$number_1 - $number_2;
}else if($operator=="*"){
$answer=$number_1 * $number_2;
}else if($operator=="%"){
$answer=$number_1 / $number_2;
}else if($operator=="/"){
if ($number_2 != 0) {
$answer = $number_1 / $number_2;
} else {
echo "Cannot divide by zero!";
exit;
}
}else{
echo "Invalid Operator";
}
echo $answer;
?>
EXPLANATION
Line 1: Declare a variable called $number_1. The variable store the first number the user want to perform the operation on.
Line 2: Declare a variable called $operator that stores the type of operator the user want to perform.
Line 3: Declare a variable called $number_2;. The variable store the second number the user want to perform the operation on.
Line 4 - 20: Check the operator entered by the user, compute the value and store the answer in $answer.
Line 21: Prints the message if the value of $operator is not +, -, *, %, or /.
Line 21: Prints out the answer after computing.
TRY IT YOURSELF
You can experiment the program using different numbers and different operators. You can further extend the program to
CONCLUSION
Congratulations you have made it to the end.- You have successfully create a simple calculator that's ready to crunch some numbers! With this project, you've not only learned the basics of PHP programming but also gained hands-on experience with arithmetic operator, conditional statements, and variables. Pat yourself on the back, because you've just taken a significant step towards becoming a PHP master! Now, go ahead and experiment with your new calculator - add more features, try new things, and most importantly, have fun with it.
Tags:
PHP