Operators
In this tutorial, I will explain the basics of PHP operators. First you have the basics addition, subtraction, multiplication and division signs: + - * /.
<?
$x = 4;
$y = 2;
$add = $x + $y;
$sub = $x - $y;
$mul = $x * $y;
$div = $x / $y;
echo "4 + 2 = $add<br />";
echo "4 - 2 = $sub<br />";
echo "4 * 2 = $mul<br />";
echo "4 / 2 = $div";
?>
This will display:
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8
4 / 2 = 2
Let's see something more interesting with comparison operators. They're most used with the if statement.
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
With $x = 4 and $y = 2...
$x == $y will return false;
$x > $y will return true. Etc.
There are also logical operators:
&& and
|| or
! not.
Still with $x = 4 and $y = 2...
$x != $y && $x > $y will result true;
$x == $y || $x < $y will result false.
Example
Here is an example of using php operators with if statement. I use Pythagoras theorem here: in the form, fill out 2 values, y and z, the script will calculate the hypotenuse length, that is to say, y^2+z^2. Try it now!
How to do it:
<?
if (!$y || !$z) {
echo '<form method="post" action="index.php">
<input type="text" name="y" /><br />
<input type="text" name="z" /><br />
<input type="submit" name="submit" />
</form>';
}
else {
$hyp = $z * $z + $y * $y;
echo '<script language="Javascript" type="text/javascript"> alert ("Your hypotenuse length is '.$hyp.' !") </script>';
} ?>
!$y || !$z: if there's no y or z defined, show the form, else, calculate the hypotenuse length: $hyp = $z * $z + $y * $y; and display it (echo). Here, I used a javascript alert to display it but you can use whatever you want!
Leave a Comment
Works? Doesn't work? Other tips? Please leave a comment! :)