PHP Expressions & Operators

Whatever you write in PHP are expressions, however, it could be an assigned value to a variable or a function which do some operations. In this lesson we are going to get more familiar with them.

Operators are signs that do something on variables and save the result into another or the same variable. These operations are some what kind of expressions.

To make Arithmetic expressions, such as summing, we have these basic operators:

  • + : Adding one value (directly or from a variable) to another
  • – : Subtracting one value from another
  • * : Multiplying one value by another
  • / : Dividing one value by another
  • % : Remained value from dividing

We use assignment signs to save a value in a variable or an array. The basic one of them that you have seen it before is ‘=’, equal sign. It gets its right-side value and saves it to the variable (or array)  on the left side. We had some examples of operators in the variables related lesson. It is not important either the variable has a value or not, once you use this sign, a new value goes into the variable. It can also be used for saving one variable value, with or without doing some operation on it, to another variable:

PHP divides the operators in the following groups:

  • Operator Precedence
  • Arithmetic operators
  • Assignment operators
  • Bitwise Operators
  • Comparison operators
  • Error Control Operators
  • Execution Operators
  • Increment/Decrements operators
  • Logical operators
  • String operators
  • Array operators
  • Type Operators

An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).

Operator Precedence

An operator precedence specifies how “tightly” it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication (“*”) operator has a higher precedence than the addition (“+”) operator. Parentheses could be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.

When operators have equal precedence their associativity decides how the operators are grouped. For example “-” is left-associative, so 1 – 2 – 3 is grouped as (1 – 2) – 3 and evaluates to -4. “=” on the other hand is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).

Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 on the other hand is legal, because the == operator has lesser precedence than the <= operator.

Use of parentheses, even when not strictly necessary, can often increase readability of the code by making grouping explicit than relying on the implicit operator precedence and associativity.

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.

AssociativityOperators
non-associativeclone new
left[
right**
right++  ~ (int) (float) (string) (array) (object) (bool) @
non-associativeinstanceof
right!
left* / %
left+  .
left<< >>
non-associative< <= > >=
non-associative== != === !== <> <=>
left&
left^
left|
left&&
left||
right??
left? :
right= += -= *= **= /= .= %= &= |= ^= <<= >>=
leftand
leftxor
leftor

PHP Arithmetic Operators

We use PHP arithmetic operators with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

Arithmetic Operators
ExampleNameResult
+$aIdentityConversion of $a to int or float as appropriate.
-$aNegationOpposite of $a.
$a + $bAdditionSum of $a and $b.
$a – $bSubtractionDifference of $a and $b.
$a * $bMultiplicationProduct of $a and $b.
$a / $bDivisionQuotient of $a and $b.
$a % $bModuloRemainder of $a divided by $b.
$a ** $bExponentiationResult of raising $a to the $b‘th power. Introduced in PHP 5.6.

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is “=”. It means that the left operand gets set to the value of the assignment expression on the right.

AssignmentSame as…Description
x = yx = yThe left operand gets set to the value of the expression on the right
x += yx = x + yAddition
x -= yx = x – ySubtraction
x *= yx = x * yMultiplication
x /= yx = x / yDivision
x %= yx = x % yModulus

Bitwise Operators

Through Bitwise operators, you can allow evaluate and manipulate  specific bits within an integer.

Bitwise Operators
ExampleNameResult
$a & $bAndBits that are set in both $a and $b are set.
$a | $bOr (inclusive or)Bits that are set in either $a or $b are set.
$a ^ $bXor (exclusive or)Bits that are set in $a or $b but not both are set.
~ $aNotBits that are set in $a are not set.
$a << $bShift leftShift the bits of $a $b steps to the left (each step means “multiply by two”)
$a >> $bShift rightShift the bits of $a $b steps to the right (each step means “divide by two”)

In order to execute the desired precedence, you have to use parenthesis.

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators
ExampleNameResult
$a == $bEqualTRUE if $a is equal to $b after type juggling.
$a === $bIdenticalTRUE if $a is equal to $b, and they are of the same type.
$a != $bNot equalTRUE if $a is not equal to $b after type juggling.
$a <> $bNot equalTRUE if $a is not equal to $b after type juggling.
$a !== $bNot identicalTRUE if $a is not equal to $b, or they are not of the same type.
$a < $bLess thanTRUE if $a is strictly less than $b.
$a > $bGreater thanTRUE if $a is strictly greater than $b.
$a <= $bLess than or equal toTRUE if $a is less than or equal to $b.
$a >= $bGreater than or equal toTRUE if $a is greater than or equal to $b.
$a <=> $bSpaceshipAn integer less than, equal to, or greater than zero when $a is respectively less than, equal to, or greater than $b. Available as of PHP 7.

PHP Increment / Decrement Operators

The PHP increment operators are used to increase or decrease a variable’s value, which is called pre / post increment / decrement respectively.

ExampleNameEffect
++$aPre-incrementIncrements $a by one, then returns $a.
$a++Post-incrementReturns $a, then increments $a by one.
–$aPre-decrementDecrements $a by one, then returns $a.
$a–Post-decrementReturns $a, then decrements $a by one.

They only work on numbers and strings and have no effect on arrays, objects and other resources.

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

ExampleNameResult
$a and $bAndTRUE if both $a and $b are TRUE.
$a or $bOrTRUE if either $a or $b is TRUE.
$a xor $bXorTRUE if either $a or $b is TRUE, but not both.
! $aNotTRUE if $a is not TRUE.
$a && $bAndTRUE if both $a and $b are TRUE.
$a || $bOrTRUE if either $a or $b is TRUE.

Point to be noted is that, “and” and “or” operate on a different precedence level. Logical operators always return a boolean value.

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2.=Concatenation assignment$txt1 .= $txt2Appends $txt2 to $txt1

PHP Array Operators

The PHP array operators are used to compare arrays.

ExampleNameResult
$a + $bUnionUnion of $a and $b.
$a == $bEqualityTRUE if $a and $b have the same key/value pairs.
$a === $bIdentityTRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $bInequalityTRUE if $a is not equal to $b.
$a <> $bInequalityTRUE if $a is not equal to $b.
$a !== $bNon-identityTRUE if $a is not identical to $b.

Type Operators

instance of is used to determine whether a PHP variable is an instantiated object of a certain class:

Example:

<?php
class MyClass
{

}
class NotMyClass
{

}

$a = new MyClass;

var_dump($a instanceof MyClass);

var_dump($a instanceof NotMyClass);

?> 

Out Put

bool(true)
bool(false)

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com