PHP Free Tutorial

Operators in PHP

In PHP, Programming by Baqir Ali

Operators in PHP

There are multiple types of operators supported by PHP. Arithmetic operators, Unary operators, Relational and Logical operators, Assignment operators, Equality operators, String Operators, and the Conditional operator.

Arithmetic Operator in PHP

  • + add two operands
  • – subtracts two operands
  • * multiplies two operands
  • / divides the first operand by the second operand
  • % remainder operator

Example 1:

<?php
$num1 = 20;
$num2 = 10;
$result = $num1 + $num2;
//echo($result);
echo("The sum is ".$result);
?>

Output: The sum is 30

Example 2:

<?php
$num1 = 20;
$num2 = 3;
$result = $num1 % $num2;
//echo($result);
echo("The remainder is ".$result);
?>

Output: The remainder is 2

String Operator(.):

The dot(.) is used to concatenate two strings in PHP.

Example 3:

<?php
	$name="Ali";
	$phrase="Your name is ".$name;
	echo "$phrase";
?>

Output: Your name is Ali

Assignment Operator in PHP

The assignment operator (=) is used to assigning values to variables.

Example 4:

<?php
	$name="Ali";
	$phrase="Your name is ".$name;
	echo "$phrase";
?>

Assigning “Ali” string value to $name

Relational or Comparison Operator in PHP

Relational operators are used to comparing two operands and return true or false as a result of the comparison. We use these operators in conditional statements and loops.

  • < less than operator
  • > greater than operator
  • <= less than or equal to operator
  • >= greater than or equal to operator
  • == (===) equal to operator

Example 5:

<?php
	$marks=55;
	if($marks>50)
		echo "Pass";
	else
		echo "Fail";
?>

Ternary Operator in PHP

A ternary operator or other than operator is an operator that needs three operands.

Example 6:

<?php
	$a=15;
	$b=25;
	$c=10;
	$max=($a>$b)?$a:$b;
	echo "Max is ".$max;
?>

Output: Max is 25

Logical Operator in PHP

Effects on relational expression’s results also AND, OR combines two or more Relational expressions,  Results will be returned either TRUE( 1 ) or FALSE ( 0 ) regards with specific situations.

These Operators are AND &&, OR ||, NOT !

Support us by sharing this post