Suscriber with us



Receive HTML?

Syndicate

PHP Operators PDF Print E-mail

Comparison Operators
 

Operator Description Example

 ==

 is equal to

 5==8 returns false

 !=

 is not equal

 5!=8 returns true

 >

 is greater than

 5>8 returns false

 <

 is less than

 5<8 returns true 

 >=

 is greater than or equal to

 5>=8 returns false

 <=

 is less than or equal to

 5<=8 returns true


Comparisons are used to check the relationship between variables and/or values. If you would like to see a simple example of a comparison operator in action, check out our If Statement Lesson. Comparison operators are used inside provisional statements and evaluate to either true or false. Here are the most important comparison operators of PHP.
Assume: $x = 4 and $y = 5;

Logical Operators

Operator Description Example

 &&

 and

 x=6
 y=3

 (x < 10 && y > 1) returns true

 ||

 or

 x=6
 y=3

 (x==5 || y==5) returns       false

 !

 not

 x=6
 y=3

 !(x==y) returns

 
String Operators

As we have already seen in the Echo Lesson, the period "." is used to add two strings together, or more technically, the period is the concatenation operator for strings.

PHP Code:

$a_string = "Hello"; 
$another_string = " Billy"; 
$new_string = $a_string . $another_string; 
echo $new_string . "!";

Display:

Hello Billy!

Combination Arithmetic & Assignment Operators

In programming it is a very common task to have to increment a variable by some fixed amount. The most common example of this is a counter. Say you want to increment a counter by 1, you would have:

  • $counter = $counter + 1;

However, there is a shorthand for doing this.

  • $counter += 1;

This combination assignment/arithmetic operator would achieve the same task. The downside to this combination operator is that it reduces code readability to those programmers who are not used to such an operator. Here are some examples of other common shorthand operators. In general, "+=" and "-=" are the most widely used combination operators.

Operator English Example Equivalent Operation

 +=

 Plus Equals

 $x += 2;

 $x = $x + 2;

 -=

 Minus Equals

 $x -= 4;

 $x = $x - 4;

 *=

 Multiply Equals

 $x *= 3;

 $x = $x * 3;

 /=

 Divide Equals

 $x /= 2;

 $x = $x / 2;

 %=

 Modulo Equals

 $x %= 5;

 $x = $x % 5;

 .=

 Concatenate Equals

 $my_str.="hello";

 $my_str = $my_str . "hello";

 


Last Updated ( Thursday, 27 March 2008 )
 
< Prev   Next >

Polls

Which is the best Scripting language?