PHP - SPLessons

PHP Operators

Chapter 9

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Operators

PHP Operators

shape Description

The PHP operators are used to perform the operations in PHP.

Arithmetic Operators

shape Description

Arithmetic operators are used to perform the arithmetic operations in PHP like addition, subtraction, multiplication and division.

shape Examples

Addition

<?php 
	$x = 30; 
	$y = 40; 
	echo $x+$y; //70
?>

Subtraction

<?php 
	$x = 30; 
	$y = 40; 
	echo $x-$y; //-10
?>

Multiplication

<?php 
	$x = 30; 
	$y = 40; 
	echo $x*$y; //1200
?>

Division

<?php 
	$x = 30; 
	$y = 40; 
	echo $x/$y; //0.75
?>

ModulusDivision

<?php 
	$x = 40; 
	$y = 30; 
	echo $x%$y; //10
?>

Exponentiation

<?php 
	$x = 4; 
	$y = 3; 
	echo $x**$y; //10
?>

Logical Operators

shape Description

In PHP, conditional statements are used as logical operators.

Name Example Details
And $a and $b Returns TRUE when both $a and $b are TRUE.
Or $a or $b Returns TRUE when either $a or $b is TRUE.
Xor $a xor $b Returns TRUE when either $a or $b is TRUE, but not both.
Not !$a Returns TRUE when $a is not TRUE.
And $a && $b Returns TRUE when both $a and $b are TRUE.
Or $a || $b Returns TRUE when either $a or $b is TRUE.

shape Examples


or Operator


<?php 
	$x = 30; 
	$y = 40; 
	if($x == 60 || $y == 40) 
	{ 
		echo "SP Lessons";  //SP Lessons
	} 
?>

and – Operator

<?php 
	$x = 30; 
	$y = 40; 
	if($x==30&&$y==40) 
	{ 
		echo "SP Lessons";  //SP Lessons
	} 
?>

Not – Operator

<?php 
	$x = 30; 
	$y = 40; 
	if($x!==120) 
	{ 
		echo "SP Lessons";  //SP Lessons
	} 
?>

Increment/Decrement Operators

shape Description

Increment and Decrement Operators increments or decrements the value assigned to a variable by 1.

Operators Operator type Description
++$x Pre-increment $x value is incremented before assigning it to variable $x
$x++ Post-increment $x is incremented after assigning it to variable $x
– -$x Pre-decrement $x value decremented before assigning it to variable $x
$x- – Post-decrement $x value decremented after assigning it to variable $x

shape Example

Postincrement

<?php
	$x = 5;
	echo "Should be 5: " . $x++ . "<br />"; //5
	echo "Should be 6: " . $x . "<br />"; //6
?>

Preincrement

<?php
	$x = 5;
	echo "Should be 5: " . ++$x . "<br />"; //6
	echo "Should be 6: " . $x . "<br />"; //5
?>

Postdecrement

<?php
	$x = 5;
	echo "Should be 5: " . $x-- . "<br />"; //5
	echo "Should be 6: " . $x . "<br />"; //4
?>

Predecrement

<?php
	$x = 5;
	echo "Should be 5: " . $x-- . "<br />"; //4
	echo "Should be 6: " . $x . "<br />"; //4
?>

Summary

shape Key Points

  • Operators takes values, performs some operations and returns new values.
  • Arithmetic,Assignment,Logical,Increment/decrement are some of the PHP operators.