You are currently browsing the page Operators in the PHP category.

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!

Print This Post Print This Post



Sponsors


Leave a Comment

Works? Doesn't work? Other tips? Please leave a comment! :)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

To post codes, please go to SimpleCode and transform your codes first, so that it will displayed properly. Indeed, < and > need to be converted to &lt; and &gt; :)


Close
E-mail It