PHP Basic: Operators

February 1, 2009 · Filed Under PHP 

If you have had previous programming experience in PHP or in any other programming language for that matter, you should be very familiar with the concept of operators. Operators allow you to manipulate data objects called operands in a number of ways. For instance you can use them to compare, assign, multiply, add, subtract, concatenate or do any mathematic functions.

Operators take the form of symbols, such as +, -, *, =, <, and >, or a combination of symbols, such as ++, –, ==, +=, and ===. An operator is used on expressions to operate on operands to produce results (values).

In PHP there are four types of operators:

Arithmetic Operators

Operator Description Example Result

+

Addition

$x = 3 + 5;

8

-

Subtraction

$x = 5 – 3;

2

*

Multiplication

$x = 3 * 4;

12

/

Division

$x = 20/4;
$x = 1/2;

5
0.5

%

Modulus (division remainder)

$x = 7%3;
$x = 6%3;

1
0

++

Increment

$x++

$x = $x + 1;

Decrement

$x–

$x = $x – 1;

Assignment Operators

Operator

Example

Result

=

$x = 45;

$x = “Hello World”;

45

Hello World

+=

$x += $y;

$x = $x + $y;

-=

$x -= $y;

$x = $x – $y;

*=

$x *= $y;

$$x = $x * $y;

/=

$x /= $y;

$x = $x / $y;

.=

$x .= $y;

$x = $x . $y;

%=

$x %= $y;

$x = $x % $y;

Comparison Operators

Operator

Description

Example

Result

==

is equal to

1==2

returns false

!=

is not equal

1!=2

returns true

===

Is identical to in value and type

7 === 7.0

returns false

!==

Is no identical to

“911” !== 911

retunes true

>

is greater than

5>9

returns false

<

is less than

3<9

returns true

>=

is greater than or equal to

4>=8

returns false

<=

is less than or equal to

4<=8

returns true

Logical Operators:

Operator

Description

Example

Result

&&

And

$z = $x && $y;

$z = $x and $y;

Returns true if both $y and $y are true

||

Or

$z = $x || $y;

$z = $x or $y;

Returns true if either $y or $y is true

xor

Xor

Returns true if either $y or $y is true, but not both

!

Not

!$x

Returns true if $x is false

NB: An expression is also a PHP statement and should always be terminated by a semicolon.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Comments

Comments are closed.