PHP Tutorial

Php advanced, mysql database, php examples, php reference, php operators.

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators
  • Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result Try it
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power

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.

Assignment Same as... Description Try it
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus

Advertisement

PHP Comparison Operators

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

Operator Name Example Result Try it
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.

Operator Same as... Description Try it
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result Try it
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result Try it
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Array Operators

The PHP array operators are used to compare arrays.

Operator Name Example Result Try it
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result Try it
?: Ternary $x = ? : Returns the value of $x.
The value of $x is if = TRUE.
The value of $x is if = FALSE
?? Null coalescing $x = ?? Returns the value of $x.
The value of $x is if exists, and is not NULL.
If does not exist, or is NULL, the value of $x is .
Introduced in PHP 7

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

PHP Assignment Operators

Php tutorial index.

PHP assignment operators applied to assign the result of an expression to a variable. = is a fundamental assignment operator in PHP. It means that the left operand gets set to the value of the assignment expression on the right.

Operator Description
= Assign
+= Increments then assigns
-= Decrements then assigns
*= Multiplies then assigns
/= Divides then assigns
%= Modulus then assigns

PHP 7 Operators with Example

This tutorial will describe PHP 7 operators with example . The Operators help to perform operations on variables and values.

There are some new operators introduced into php 7, like the null coalescing operator ( ?? ), spaceship operator( <=> ).

Here, We will discuss all php7 operators with examples. We will go through one by one operator types in PHP 7. There are the following operator groups available in PHP 7.

PHP Arithmetic Operators

OperatorNameExampleDescription
+Addition$x + $ySum of $x and $y
Subtraction$x – $yDifference of $x and $y
*Multiplication$x * $yProduct of $x and $y
/Division$x / $yQuotient of $x and $y
%Modulus$x % $yRemainder of $x divided by $y
**Exponentiation$x ** $yResult of raising $x to the $y’th power

PHP 7 Arithmetic Operators Example

Php 7 assignment operators.

This type php 7 operator are used to assign values to variables.The left operands gets set to the value of the assignment expression on the right.

Assignment OperatorSame asDescription
$x = $y$x = $yThe assign right expression values to the left variable.
$x += $y$x = $x + $yAddition and assign value to left variable($x).
$x -= $y$x = $x – $ySubtraction and assign value to left variable($x)
$x *= $y$x = $x * $yMultiplication and assign value to $x.
$x /= $y$x = $x / $yDivision and assign value to $x
$x %= $y$x = $x % $yModulus and assign value to $x

PHP 7 Assignment Operators Example

Php comparison operators.

The PHP 7 Comparison Operators help to compare two variables. You can also compare two different types of variables as well.

OperatorNameUsesResult
==Equal$x == $yReturns true, if $x is equal to $y
===Identical$x === $yReturns true, if $x is equal to $y with same type
!=Not equal$x != $yReturns true, if $x is not equal to $y
<>Not equal$x <> $yReturns true, if $x is not equal to $y
!==Not identical$x !== $yReturns true, if $x is not equal to $y, or they are not of the same type
>Greater than$x > $yReturns true, if $x is greater than $y
<Less than$x < $yReturns true if, $x is less than $y
>=Greater than or equal to$x >= $yReturns true, if $x is greater than or equal to $y
<=Less than or equal to$x <= $yReturns true, if $x is less than or equal to $y

PHP 7 comparison Operators Example

Php 7 increment / decrement operators.

The PHP 7 increment operators are used to increment a variable’s value whereas Decrement Operators used to decrement a variable’s value.

OperatorNameDescription
++$xPre-incrementIncrements $x by one, then returns $x
$x++Post-incrementReturns $x, then increments $x by one
–$xPre-decrementDecrements $x by one, then returns $x
$x–Post-decrementReturns $x, then decrements $x by one

PHP 7 Incrementing and Decrementing Operators Example

Php 7 logical operators.

The PHP 7 logical operators are used to combine two conditions. You can combine two variable conditions using logical operators.

OperatorNameExampleResult
andAnd$x and $yTrue – if both $x and $y are true
orOr$x or $yTrue – if either $x or $y is true
xorXor$x xor $yTrue – if either $x or $y is true, but not both
&&And$x && $yTrue – if both $x and $y are true
||Or$x || $yTrue – if either $x or $y is true
!Not!$xTrue – if $x is not true

PHP 7 Logical Operators Example

Php 7 string operators.

There are the following operators for string manipulation.Its specially designed for string types variables.

OperatorNameExampleResult
.Concatenation$str1 . $str2Concatenation of $str1 and $str2
.=Concatenation assignment$str1 .= $str2Appends $str2 to $str1

PHP 7 String Operators Example

Php 7 array operators.

PHP 7 also provides operators for array type variables, you can compare two arrays using the following array operators.

OperatorNameExampleResult
+Union$x + $yUnion of $x and $y
==Equality$x == $yReturns true, if $x and $y have the same key/value pairs
===Identity$x === $yReturns true, if $x and $y have the same key/value pairs in the same order and of the same types
!=Inequality$x != $yReturns true, if $x is not equal to $y
<>Inequality$x <> $yReturns true, if $x is not equal to $y
!==Non-identity$x !== $yReturns true, if $x is not identical to $y

PHP 7 Conditional Assignment Operators

OperatorNameExampleResult
?:Ternary$x = 3 > 2 ? true : falseReturns the value of $x based on condition.
??Null coalescing$x = $a > $b ?? $a : $bReturns the value of $x.
The value of $x is $a if $a
exists, and is not NULL. If $a does not exist, or is NULL, the value of $x is
$b.

PHP 7 Conditional Assignment Operators Example

Php 7 spaceship operator.

These operators are introduced into PHP 7. The operand (<=>) is used for comparing two expressions. This is a three-way comparison operator and it can perform greater than, less than, and equal comparisons between two operands.

The spaceship operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater.

PHP 7 Spaceship Operator Example

2 thoughts on “ php 7 operators with example ”, leave a reply cancel reply.

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • PHP Tutorial
  • PHP Install
  • PHP Hello World
  • Check if variable is set
  • Convert string to int
  • Convert string to float
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Get type of variable
  • Subtraction
  • Multiplication
  • Exponentiation
  • Simple Assignment
  • Addition Assignment
  • Subtraction Assignment
  • ADVERTISEMENT
  • Multiplication Assignment
  • Division Assignment
  • Modulus Assignment
  • PHP Comments
  • Python If AND
  • Python If OR
  • Python If NOT
  • Do-While Loop
  • Nested foreach
  • echo() vs print()
  • printf() vs sprintf()
  • PHP Strings
  • Create a string
  • Create empty string
  • Compare strings
  • Count number of words in string
  • Get ASCII value of a character
  • Iterate over characters of a string
  • Iterate over words of a string
  • Print string to console
  • String length
  • Substring of a string
  • Check if string is empty
  • Check if strings are equal
  • Check if strings are equal ignoring case
  • Check if string contains specified substring
  • Check if string starts with specific substring
  • Check if string ends with specific substring
  • Check if string starts with specific character
  • Check if string starts with http
  • Check if string starts with a number
  • Check if string starts with an uppercase
  • Check if string starts with a lowercase
  • Check if string ends with a punctuation
  • Check if string ends with forward slash (/) character
  • Check if string contains number(s)
  • Check if string contains only alphabets
  • Check if string contains only numeric digits
  • Check if string contains only lowercase
  • Check if string contains only uppercase
  • Check if string value is a valid number
  • Check if string is a float value
  • Append a string with suffix string
  • Prepend a string with prefix string
  • Concatenate strings
  • Concatenate string and number
  • Insert character at specific index in string
  • Insert substring at specific index in string
  • Repeat string for N times
  • Replace substring
  • Replace first occurrence
  • Replace last occurrence
  • Trim spaces from edges of string
  • Trim specific characters from edges of the string
  • Split string
  • Split string into words
  • Split string by comma
  • Split string by single space
  • Split string by new line
  • Split string by any whitespace character
  • Split string by one or more whitespace characters
  • Split string into substrings of specified length
  • Transformations
  • Reverse a string
  • Convert string to lowercase
  • Convert string to uppercase
  • Join elements of string array with separator string
  • Delete first character of string
  • Delete last character of string
  • Count number of occurrences of substring in a string
  • Count alphabet characters in a string
  • Find index of substring in a string
  • Find index of last occurrence in a string
  • Find all the substrings that match a pattern
  • Check if entire string matches a regular expression
  • Check if string has a match for regular expression
  • Sort array of strings
  • Sort strings in array based on length
  • Foramatting
  • PHP – Format string
  • PHP – Variable inside a string
  • PHP – Parse JSON String
  • Conversions
  • PHP – Convert CSV String into Array
  • PHP – Convert string array to CSV string
  • Introduction to Arrays
  • Indexed arrays
  • Associative arrays
  • Multi-dimensional arrays
  • String array
  • Array length
  • Create Arrays
  • Create indexed array
  • Create associative array
  • Create empty array
  • Check if array is empty
  • Check if specific element is present in array .
  • Check if two arrays are equal
  • Check if any two adjacent values are same
  • Read/Access Operations
  • Access array elements using index
  • Iterate through array using For loop
  • Iterate over key-value pairs using foreach
  • Array foreach()
  • Get first element in array
  • Get last element in array
  • Get keys of array
  • Get index of a key in array
  • Find Operations
  • Count occurrences of specific value in array
  • Find index of value in array
  • Find index of last occurrence of value in array
  • Combine two arrays to create an Associative Array
  • Convert array to string
  • Convert array to CSV string
  • Join array elements
  • Reverse an array
  • Split array into chunks
  • Slice array by index
  • Slice array by key
  • Preserve keys while slicing array
  • Truncate array
  • Remove duplicate values in array
  • Filter elements in array based on a condition
  • Filter positive numbers in array
  • Filter negative numbers in array
  • Remove empty strings in array
  • Delete Operations
  • Delete specific value from array
  • Delete value at specific index in array
  • Remove first value in array
  • Remove last value in array
  • Array - Notice: Undefined offset: 0
  • JSON encode
  • Array Functions
  • array_chunk()
  • array_column()
  • array_combine()
  • array_change_key_case()
  • array_count_values()
  • array_diff_assoc()
  • array_diff_key()
  • array_diff_uassoc()
  • array_diff_ukey()
  • array_diff()
  • array_fill()
  • array_fill_keys()
  • array_flip()
  • array_key_exists()
  • array_keys()
  • array_pop()
  • array_product()
  • array_push()
  • array_rand()
  • array_replace()
  • array_sum()
  • array_values()
  • Create an object or instance
  • Constructor
  • Constants in class
  • Read only properties in class
  • Encapsulation
  • Inheritance
  • Define property and method with same name in class
  • Uncaught Error: Cannot access protected property
  • Nested try catch
  • Multiple catch blocks
  • Catch multiple exceptions in a single catch block
  • Print exception message
  • Throw exception
  • User defined Exception
  • Get current timestamp
  • Get difference between two given dates
  • Find number of days between two given dates
  • Add specific number of days to given date
  • ❯ PHP Tutorial
  • ❯ PHP Operators
  • ❯ Assignment

PHP Assignment Operators

In this tutorial, you shall learn about Assignment Operators in PHP, different Assignment Operators available in PHP, their symbols, and how to use them in PHP programs, with examples.

Assignment Operators

Assignment Operators are used to perform to assign a value or modified value to a variable.

Assignment Operators Table

The following table lists out all the assignment operators in PHP programming.

OperatorSymbolExampleDescription
Simple Assignment=x = 5Assigns value of 5 to variable x.
Addition Assignment+= Assigns the result of to x.
Subtraction Assignment-= Assigns the result of to x.
Multiplication Assignment*= Assigns the result of to x.
Division Assignment/= Assigns the result of to x.
Modulus Assignment%= Assigns the result of to x.

In the following program, we will take values in variables $x and $y , and perform assignment operations on these values using PHP Assignment Operators.

PHP Program

Assignment Operators in PHP

Assignment Operators Tutorials

The following tutorials cover each of the Assignment Operators in PHP in detail with examples.

  • PHP Simple Assignment
  • PHP Addition Assignment
  • PHP Subtraction Assignment
  • PHP Multiplication Assignment
  • PHP Division Assignment
  • PHP Modulus Assignment

In this PHP Tutorial , we learned about all the Assignment Operators in PHP programming, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

CodedTag

  • Assignment Operators

PHP assignment operators enable you to frequently engage in performing calculations and operations on variables, requiring the assignment of results to other variables. Consequently, this is precisely where assignment operators prove indispensable, allowing you to seamlessly execute an operation and assign the result to a variable within a single statement.

In the following sections, we’ll delve into the different types of PHP assignment operators and explore how to use them.

Table of Contents

Php arithmetic assignment operators, php bitwise assignment operators.

  • Null Coalescing Operator

Assigning a Reference to a PHP Variable

Other assignment operators, wrapping up.

The most commonly used assignment operator in PHP is the equals sign (=). For instance, in the following code, the value 10 is assigned to the variable $x:

Now, let’s explore each type with examples:

Numeric data undergoes mathematical operations through the utilization of arithmetic operators. In PHP, this is where arithmetic assignment operators come into play, employed to perform these operations. The arithmetic assignment operators include:

  • += or $x + $y (Addition Assignment Operator)
  • -= or $x - $y (Subtraction Assignment Operator)
  • *= or $x * $y (Multiplication Assignment Operator)
  • /= or $x / $y (Division Assignment Operator)
  • %= or $x % $y (Modulus Assignment Operator)
  • **= or $x ** $y (Exponentiation Assignment Operator)

Consider the following example:

In this example, the addition assignment operator increases the value of $x by 5, and then assigns the result back to $x, producing an output of 15.

You can leverage these arithmetic assignment operators to perform complex calculations in a single statement, making your code more concise and easier to read. For more details, refer to this tutorial .

One crucial aspect of computer science involves the manipulation of binary bits in PHP. Let’s delve into one of the more complex assignment operators—specifically, the PHP bitwise operators.

Developers use bitwise operators to manipulate data at the bit level. PHP bitwise assignment operators perform bitwise operations. Here are the bitwise assignment operators:

  • &= or $x & $y (Bitwise AND Assignment Operator)
  • |= or $x | $y (Bitwise OR Assignment Operator)
  • ^= or $x ^ $y (Bitwise XOR Assignment Operator)
  • ~= or $x ~ $y (Bitwise NOT Assignment Operator)
  • <<= or $x << $y (Left Shift Assignment Operator)
  • >>= or $x >> $y (Right Shift Assignment Operator)

Let’s illustrate with an example:

In this example, a bitwise OR operation is performed between the values of $x and 2 using the bitwise OR assignment operator. The result is then assigned to $x, yielding an output of 7.

Here is a full explanation along with more examples of bitwise operators .

Let’s move to the section below to understand the Null Coalescing Operator in PHP.

Furthermore, developers use the null coalescing operator to assign a default value to a variable if it is null. The double question mark (??) symbolizes the null coalescing operator. Consider the following example:

In this example, the null coalescing operator is used to assign the value ‘John Doe’ to the variable $fullName. If $name is null, the value ‘John Doe’ will be assigned to $fullName.

The null coalescing operator simplifies code by enabling the assignment of default values to variables. By reading this tutorial , you will gain more information about it

Anyway, assigning a reference in PHP is one of the language’s benefits, enabling developers to set a value and refer back to it anywhere during the script-writing process. Let’s move to the section below to take a closer look at this concept.

Furthermore, individuals use the reference assignment operator =& to assign a reference to a variable rather than copying the value of the variable. Consider the following example:

In this example, a reference to the variable $x is created using the reference assignment operator. The value 10 is then assigned to $x, and the output displays the value of $y. Since $y is a reference to $x, it also changes to 10, resulting in an output of 10.

The reference assignment operator proves useful when working with large data sets, enabling you to avoid copying large amounts of data.

Let’s explore some other assignment operators in the paragraphs below.

In addition to the arithmetic, bitwise, null coalescing, and reference assignment operators, PHP provides other assignment operators for specific use cases. These operators are:

  • .= (Concatenation Assignment Operator)
  • ??= (Null Coalescing Assignment Operator)

Now, let’s explore each of these operators in turn:

Concatenation Assignment Operator: Used to concatenate a string onto the end of another string. For example:

In this example, the concatenation assignment operator appends the value of $string2 to the end of $string1, resulting in the output “Hello World!”.

The Null Coalescing Assignment Operator is employed to assign a default value to a variable when it is detected as null. For example:

In this example, the null coalescing assignment operator assigns the value ‘John Doe’ to the variable $name. If $name is null, the value ‘John Doe’ will be assigned to $name.

Let’s summarize it.

we’ve taken a comprehensive look at the different types of PHP assignment operators and how to use them. Assignment operators are essential tools for any PHP developer, facilitating calculations and operations on variables while assigning results to other variables in a single statement.

Moreover, leveraging assignment operators allows you to make your code more concise, easier to read, and helps in avoiding common programming errors.

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • Install PHP
  • Hello World
  • PHP Constant
  • PHP Comments

PHP Functions

  • Parameters and Arguments
  • Anonymous Functions
  • Variable Function
  • Arrow Functions
  • Variadic Functions
  • Named Arguments
  • Callable Vs Callback
  • Variable Scope

Control Structures

  • If-else Block
  • Break Statement

PHP Operators

  • Operator Precedence
  • PHP Arithmetic Operators
  • PHP Bitwise Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators
  • Conditional Operators
  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator

Data Format and Types

  • PHP Data Types
  • PHP Type Juggling
  • PHP Type Casting
  • PHP strict_types
  • Type Hinting
  • PHP Boolean Type
  • PHP Iterable
  • PHP Resource
  • Associative Arrays
  • Multidimensional Array

String and Patterns

  • Remove the Last Char

Other Tutorials

  • If Condition
  • require_once & require
  • array_map()
  • Elvis Operator
  • Predefined Constants
  • PHP History

PHP Operators

In this tutorial you will learn how to manipulate or perform the operations on variables and values using operators in PHP.

What is Operators in PHP

Operators are symbols that tell the PHP processor to perform certain actions. For example, the addition ( + ) symbol is an operator that tells PHP to add two variables or values, while the greater-than ( > ) symbol is an operator that tells PHP to compare two values.

The following lists describe the different operators used in PHP.

PHP Arithmetic Operators

The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Here's a complete list of PHP's arithmetic operators:

Operator Description Example Result
Addition Sum of $x and $y
Subtraction Difference of $x and $y.
Multiplication Product of $x and $y.
Division Quotient of $x and $y
Modulus Remainder of $x divided by $y

The following example will show you these arithmetic operators in action:

PHP Assignment Operators

The assignment operators are used to assign values to variables.

Operator Description Example Is The Same As
Assign
Add and assign
Subtract and assign
Multiply and assign
Divide and assign quotient
Divide and assign modulus

The following example will show you these assignment operators in action:

PHP Comparison Operators

The comparison operators are used to compare two values in a Boolean fashion.

Operator Name Example Result
Equal True if $x is equal to $y
Identical True if $x is equal to $y, and they are of the same type
Not equal True if $x is not equal to $y
Not equal True if $x is not equal to $y
Not identical True if $x is not equal to $y, or they are not of the same type
Less than True if $x is less than $y
Greater than True if $x is greater than $y
Greater than or equal to True if $x is greater than or equal to $y
Less than or equal to True if $x is less than or equal to $y

The following example will show you these comparison operators in action:

PHP Incrementing and Decrementing Operators

The increment/decrement operators are used to increment/decrement a variable's value.

Operator Name Effect
Pre-increment Increments $x by one, then returns $x
Post-increment Returns $x, then increments $x by one
Pre-decrement Decrements $x by one, then returns $x
Post-decrement Returns $x, then decrements $x by one

The following example will show you these increment and decrement operators in action:

PHP Logical Operators

The logical operators are typically used to combine conditional statements.

Operator Name Example Result
And True if both $x and $y are true
Or True if either $x or $y is true
Xor True if either $x or $y is true, but not both
And True if both $x and $y are true
Or True if either $x or $y is true
Not True if $x is not true

The following example will show you these logical operators in action:

PHP String Operators

There are two operators which are specifically designed for strings .

Operator Description Example Result
Concatenation Concatenation of $str1 and $str2
Concatenation assignment Appends the $str2 to the $str1

The following example will show you these string operators in action:

PHP Array Operators

The array operators are used to compare arrays:

Operator Name Example Result
Union Union of $x and $y
Equality True if $x and $y have the same key/value pairs
Identity True if $x and $y have the same key/value pairs in the same order and of the same types
Inequality True if $x is not equal to $y
Inequality True if $x is not equal to $y
Non-identity True if $x is not identical to $y

The following example will show you these array operators in action:

PHP Spaceship Operator PHP 7

PHP 7 introduces a new spaceship operator ( <=> ) which can be used for comparing two expressions. It is also known as combined comparison operator.

The spaceship operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It basically provides three-way comparison as shown in the following table:

Operator Equivalent

The following example will show you how spaceship operator actually works:

Bootstrap UI Design Templates

Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.

Interactive Tools

BMC

  • PHP Tutorial
  • PHP Exercises
  • PHP Calendar
  • PHP Filesystem
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP IntlChar
  • PHP Image Processing
  • PHP Formatter
  • Web Technology

PHP Operators

In this article, we will see how to use the operators in PHP, & various available operators along with understanding their implementation through the examples.

Operators are used to performing operations on some values. In other words, we can describe operators as something that takes some values, performs some operation on them, and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and 2, performs an addition operation on them to give 3. 

Just like any other programming language, PHP also supports various types of operations like arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc), Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform such operations on various operands or variables, or values. These operators are nothing but symbols needed to perform operations of various types. Given below are the various groups of operators:

  • Arithmetic Operators
  • Logical or Relational Operators
  • Comparison Operators
  • Conditional or Ternary Operators
  • Assignment Operators
  • Spaceship Operators (Introduced in PHP 7)
  • Array Operators
  • Increment/Decrement Operators
  • String Operators

Let us now learn about each of these operators in detail.

Arithmetic Operators: 

The arithmetic operators are used to perform simple mathematical operations like addition, subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax and operations in PHP.

+

Addition

$x + $y

Sum the operands

Subtraction

$x – $y

Differences the operands

*

Multiplication

$x * $y

Product of the operands

/

Division

$x / $y

The quotient of the operands

**

Exponentiation

$x ** $y

$x raised to the power $y

%

Modulus

$x % $y

The remainder of the operands

Note : The exponentiation has been introduced in PHP 5.6. 

Example : This example explains the arithmetic operator in PHP.

Logical or Relational Operators:

These are basically used to operate with conditional statements and expressions. Conditional statements are based on conditions. Also, a condition can either be met or cannot be met so the result of a conditional statement can either be true or false. Here are the logical operators along with their syntax and operations in PHP.

andLogical AND$x and $yTrue if both the operands are true else false
orLogical OR$x or $yTrue if either of the operands is true else false
xorLogical XOR$x xor $yTrue if either of the operands is true and false if both are true
&&Logical AND$x && $yTrue if both the operands are true else false
||Logical OR$x || $yTrue if either of the operands is true else false
!Logical NOT!$xTrue if $x is false

Example : This example describes the logical & relational operator in PHP.

Comparison Operators: These operators are used to compare two elements and outputs the result in boolean form. Here are the comparison operators along with their syntax and operations in PHP.

OperatorNameSyntaxOperation
==Equal To$x == $yReturns True if both the operands are equal
!=Not Equal To$x != $yReturns True if both the operands are not equal
<>Not Equal To$x <> $yReturns True if both the operands are unequal
===Identical$x === $yReturns True if both the operands are equal and are of the same type
!==Not Identical$x == $yReturns True if both the operands are unequal and are of different types
<Less Than$x < $yReturns True if $x is less than $y
>Greater Than$x > $yReturns True if $x is greater than $y
<=Less Than or Equal To$x <= $yReturns True if $x is less than or equal to $y
>=Greater Than or Equal To$x >= $yReturns True if $x is greater than or equal to $y

Example : This example describes the comparison operator in PHP.

Conditional or Ternary Operators :

These operators are used to compare two values and take either of the results simultaneously, depending on whether the outcome is TRUE or FALSE. These are also used as a shorthand notation for if…else statement that we will read in the article on decision making. 

Here, the condition will either evaluate as true or false. If the condition evaluates to True, then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

?:

Ternary

If the condition is true? then $x : or else $y. This means that if the condition is true then the left result of the colon is accepted otherwise the result is on right.

Example : This example describes the Conditional or Ternary operators in PHP.

Assignment Operators: These operators are used to assign values to different variables, with or without mid-operations. Here are the assignment operators along with their syntax and operations, that PHP provides for the operations.

=

Assign

$x = $y

Operand on the left obtains the value of the operand on the right

+=

Add then Assign

$x += $y

Simple Addition same as $x = $x + $y

-=

Subtract then Assign

$x -= $y

Simple subtraction same as $x = $x – $y

*=

Multiply then Assign

$x *= $y

Simple product same as $x = $x * $y

/=

Divide then Assign (quotient)

$x /= $y

Simple division same as $x = $x / $y

%=

Divide then Assign (remainder)

$x %= $y

Simple division same as $x = $x % $y

Example : This example describes the assignment operator in PHP.

Array Operators: These operators are used in the case of arrays. Here are the array operators along with their syntax and operations, that PHP provides for the array operation.

+

Union

$x + $y

Union of both i.e., $x and $y

==

Equality

$x == $y

Returns true if both has same key-value pair

!=

Inequality

$x != $y

Returns True if both are unequal

===

Identity

$x === $y

Returns True if both have the same key-value pair in the same order and of the same type

!==

Non-Identity

$x !== $y

Returns True if both are not identical to each other

<>

Inequality

$x <> $y

Returns True if both are unequal

Example : This example describes the array operation in PHP.

Increment/Decrement Operators: These are called the unary operators as they work on single operands. These are used to increment or decrement values.

++Pre-Increment++$xFirst increments $x by one, then return $x
Pre-Decrement–$xFirst decrements $x by one, then return $x
++Post-Increment$x++First returns $x, then increment it by one
Post-Decrement$x–First returns $x, then decrement it by one

Example : This example describes the Increment/Decrement operators in PHP. 

String Operators: This operator is used for the concatenation of 2 or more strings using the concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the right side to the argument on the left side.

.Concatenation$x.$yConcatenated $x and $y
.=Concatenation and assignment$x.=$yFirst concatenates then assigns, same as $x = $x.$y

Example : This example describes the string operator in PHP.

Spaceship Operators :

PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator or combined comparison operator is denoted by “<=>“. These operators are used to compare values but instead of returning the boolean results, it returns integer values. If both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is greater, it returns 1. The following table shows how it works in detail:

$x < $y$x <=> $yIdentical to -1 (right is greater)
$x > $y$x <=> $yIdentical to 1 (left is greater)
$x <= $y$x <=> $yIdentical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y$x <=> $yIdentical to 1 (if left is greater) or identical to 0 (if both are equal)
$x == $y$x <=> $yIdentical to 0 (both are equal)
$x != $y$x <=> $yNot Identical to 0

Example : This example illustrates the use of the spaceship operator in PHP.

Please Login to comment...

Similar reads.

  • Web Technologies
  • PHP-Operators
  • Top Android Apps for 2024
  • Top Cell Phone Signal Boosters in 2024
  • Best Travel Apps (Paid & Free) in 2024
  • The Best Smart Home Devices for 2024
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Ternary and Ternary Coalescing Operator in PHP

PHP supports various forms of ternary and coalescing operators. This is a quick post to catch-up to all ternary and coalescing operators supports in PHP.

1. Ternary Operator: cond ? expr1 : expr2

Ternary operator is a short form for an if/else block that executes exactly one expression each.

The if/else block above is quite verbose and consumes more space for a simple expression. With the ternary operator, you can optimize this:

Its syntax is follows:

PHP will execute condition condition, and if it evaluates to "true-ish" value (same semantics as an if() condition), value from expression-if-true is used. If condition evaluates to false, value from expression-if-false will be used.

An ideal use case of Ternary operator would be assignments that can have two values.

From PHP 8.0+, you can also throw an exception from a Ternary operator .

2. Shorthand Ternary Operator: cond ?: else-expr

Certain Ternary operator expressions can be simplified further. Consider the following Ternary expression:

If the conditional expression is the same as the true-expression, it is possible to reduce this further:

If load_user() function returns a false-ish value, $user will be assigned false . Otherwise, the return value of load_user() will be assigned.

Its syntax is:

The cond condition will be evaluated as if it's in an if() block, and the return value will be assigned to result if it is a truthy value. If it's a false-ish value (such as 0 , "0" , false , null , [] , etc), the expression-if-false expression will be evaluated, and its return value will be assigned to result .

3. Null Coalescing Operator

Null Coalescing Operator provides a shorthand for isset() calls. It is often used to reduce excessive isset() calls. Null Coalescing operator calls isset() on the conditional expression, and the value will be returned.

If $_GET['value'] is set (which behaves exactly the way isset() does), $_GET['value'] value will be assigned to $result . If it is not set, or null , foo will be assigned to $result .

PHP calls isset(variable) , and variable will be assigned to result if variable is set. If it is not set, expression will be evaluated, and its value will be assigned to result .

4. Null Coalescing Assignment operator

Null Coalescing operator can be be further reduced in PHP 7.4, with Null Coalescing Assignment operator .

A word of caution

Be mindful when you chain ternary/coalescing operators. It is now required to use braces to make the intent clear if you absolutely have to use ternary/coalescing operators.

Null Coalescing Assignment operator is relatively new in PHP (added in PHP 7.4), so you code might not work in older PHP versions if you decide to use that operator.

These operators are syntax sugar only, and do not provide any meaningful performance difference compared to good ol' if/else blocks. When the intent is not clear, it is recommended to go with if/else blocks although they make the code slightly verbose

Recent Articles on PHP.Watch

How to fix `mysql_native_password` not loaded errors on MySQL 8.4

How to fix mysql_native_password not loaded errors on MySQL 8.4

How to fix PHP Curl HTTPS Certificate Authority issues on Windows

How to fix PHP Curl HTTPS Certificate Authority issues on Windows

AEGIS Encryption with PHP Sodium Extension

AEGIS Encryption with PHP Sodium Extension

You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what's changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.

In PHP 7.0, we got new null coalescing operator ( ?? ) which is a syntactic sugar of using isset() for check a value for null. PHP 7.4 has brought new syntactic sugar to assign default value to a variable if it is null.

Lets say, we have a variable called $student_name which should contain student name in it. But for some reason, sometimes student name may can't be found (null value), so we need to assign default value to it before using it. In PHP <7.4 , we would do something like this:

In line 5, we are checking if $student_name has been set, if not we are assigning 'Default Name' to it.

In PHP 7.4, we can use Null Coalescing Assignment Operator (??=) to do the same:

Above, Null Coalescing Assignment Operator checks if $student_name is null, if so it assign string(12) "Default Name" to it.

Best benefit of Null Coalescing Assignment Operator is when used for array element. lets say, we have an variable for a blog post which is array

Write comment about this article:

PHP Advance

Operators - php basics.

Operators are symbols that instruct the PHP processor to carry out specific actions. For example, the addition ( + ) symbol instructs PHP to add two variables or values, whereas the greater-than ( > ) symbol instructs PHP to compare two values.

PHP operators are grouped as follows:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators
  • Conditional assignment operators

Arithmetic Operators

The PHP arithmetic operators are used in conjunction with numeric values to perform common arithmetic operations such as addition, subtraction, multiplication, and so on.

Operator Name Example Output
Addition $x + $y Sum of and
Subtraction $x - $y Difference of and
Multiplication $x * $y Product of and
Division $x / $y Quotient of and
Modulus $x % $y Remainder of divided by
Exponentiation $x ** $y Result of raising to the 'th power

Sample usage of Arithmetic Operators:

Assignment Operators

Assignment operators are used to assign values to variables.

Operator Name Example Output
Assign $x = $y The left operand gets set to the value of the expression on the right
Add and assign $x += $y Addition
Subtract and assign $x -= $y Subtraction
Multiply and assign $x *= $y Multiplication
Divide and assign quotient $x /= $y Division
Divide and assign modulus Modulus

Sample usage of Assignment Operators:

Comparison Operators

Comparison operators are used to compare two values in a Boolean fashion.

Operator Name Example Output
Equal $x == $y True if is equal to
Identical $x === $y True if is equal to , and they are of the same type
Not equal $x != $y True if is not equal to
Not equal $x <> $y True if is not equal to
Not identical $x !== $y True if is not equal to , or they are not of the same type
Less than $x < $y True if is less than
Greater than $x > $y True if is greater than
Greater than or equal to $x >= $y True if is greater than or equal to
Less than or equal to $x <= $y True if is less than or equal to

Sample usage of Comparison Operators:

Increment / Decrement Operators

Increment operators are used to increment a variable's value while decrement operators are used to decrement.

Operator Name Output
Pre-increment Increments by one, then returns
Post-increment Returns , then increments by one
Pre-decrement Decrements by one, then returns
Post-decrement Returns , then decrements by one

Sample usage of Increment / Decrement Operators:

Logical Operators

Logical operators are typically used to combine conditional statements.

Operator Name Example Output
And $x and $y if both and are
Or $x or $y if either or is
Xor $x xor $y if either or is , but not both
And $x && $y if both and are
` ` Or
Not !$x if is not

Sample usage of Logical Operators:

String Operators

String operators are specifically designed for strings.

Operator Name Example Output
Concatenation $str1 . $str2 Concatenation of and
Concatenation assignment $str1 .= $str2 Appends the to the

Sample usage of String Operators:

Array Operators

Array operators are used to compare arrays.

Operator Name Example Output
Union $x + $y Union of and
Equality $x == $y True if and have the same key/value pairs
Identity $x === $y True if and have the same key/value pairs in the same order and of the same types
Inequality $x != $y True if is not equal to
Inequality $x <> $y True if is not equal to
Non-identity $x !== $y True if is not identical to

Conditional Assignment Operators

Conditional assignment operators are used to set a value depending on conditions.

Operator Name Example Output
Ternary $x = expr1 ? expr2 : expr3 Returns the value of . The value of is expr2 if expr1 = . The value of is expr3 if expr1 =
Null coalescing $x = expr1 ?? expr2 Returns the value of . The value of is expr1 if expr1 exists, and is not . If expr1 does not exist, or is , the value of is expr2. Introduced in PHP 7

Sample usage of Conditional Assignment Operators:

Create the following variables: $num1 , $num2 , $num3 . Assign the integer 3 to $num1 and 9 to $num2 . Multiply $num1 by $num2 and assign the product to $num3 . Print the result on $num3

  • Introduction
  • What is PHP?
  • What can you do with PHP?
  • Why use PHP?
  • Requirements for this tutorial
  • Echo and Print
  • Conditionals
  • Switch...Case
  • Foreach Loop
  • Do...While Loop
  • Break/Continue
  • Sorting Arrays
  • Date and Time
  • Include Files
  • File Handling
  • File Upload
  • Form Validation
  • Error Handling
  • Classes and Objects
  • Constructor and Destructor
  • Access Modifiers
  • Inheritance
  • Abstract Classes

PHP Functions and Methods

  • PHP Functions and Methods Index
  • Language Reference

String Operators

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' .= '), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

<?php $a = "Hello " ; $b = $a . "World!" ; // now $b contains "Hello World!" $a = "Hello " ; $a .= "World!" ; // now $a contains "Hello World!" ?>

  • String type
  • String functions

Improve This Page

User contributed notes 6 notes.

To Top

Home » PHP Tutorial » PHP Null Coalescing Operator

PHP Null Coalescing Operator

Summary : in this tutorial, you’ll learn about the PHP Null coalescing operator to assign a value to a variable if the variable doesn’t exist or null.

Introduction to the PHP null coalescing operator

When working with forms , you often need to check if a variable exists in the $_GET or $_POST by using the ternary operator in conjunction with the isset() construct. For example:

This example assigns the $_POST['name'] to the $name variable if $_POST['name'] exists and not null. Otherwise, it assigns the '' to the $name variable.

To make it more convenient, PHP 7.0 added support for a null coalescing operator that is syntactic sugar of a ternary operator and isset() :

In this example, the ?? is the null coalescing operator. It accepts two operands. If the first operand is null or doesn’t exist, the null coalescing operator returns the second operand. Otherwise, it returns the first one.

In the above example, if the variable name doesn’t exist in the $_POST array or it is null, the ?? operator will assign the string 'John' to the $name variable. See the following example:

As you can see clearly from the output, the ?? operator is like a gate that doesn’t allow null to pass through.

Stacking the PHP Null coalescing operators

PHP allows you to stack the null coalescing operators. For example:

In this example, since the $fullname , $first , and $last doesn’t exist, the $name will take the 'John' value.

PHP null coalescing assignment operator

The following example uses the null coalesing operator to assign the 0 to $counter if it is null or doesn’t exist:

The above statement repeats the variable $counter twice. To make it more concise, PHP 7.4 introduced the null coalescing assignment operator ( ??= ):

In this example, the ??= is the null coalescing assignment operator. It assigns the right operand to the left if the left operand is null. Otherwise, the coalescing assignment operator will do nothing.

It’s equivalent to the following:

In practice, you’ll use the null coalescing assignment operator to assign a default value to a variable if it is null.

  • The null coalescing operator ( ?? ) is a syntactic sugar of the ternary operator and isset() .
  • The null coalescing assignment operator assigns the right operand to the left one if the left operand is null.
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Boolean assignment operators in PHP

I find myself doing this kind of thing somewhat often:

With bitwise operators, you can use the &= and |= shorthand:

Given that bitwise operations on 1 and 0 are functionally equivalent to boolean operations on true and false , we can rely on type-casting and do something like this:

...but that's pretty ugly and defeats the purpose of using a shorthand assignment syntax, since we have to use another statement to get the type back to boolean.

What I'd really like to do is something like this:

...but &&= and ||= are not valid operators, obviously. So, my question is - is there some other sugary syntax or maybe an obscure core function that might serve as a stand-in? With variables as short as $foo , it's not a big deal to just use $foo = $foo && false syntax, but array elements with multiple dimensions, and/or object method calls can make the syntax quite lengthy.

  • boolean-logic
  • syntactic-sugar

FtDRbwLXw6's user avatar

  • What is wrong with $foo = $foo && false;? Or is it just curiosity? –  Dany Caissy Commented Jul 9, 2013 at 16:08
  • 2 @DanyCaissy: I explained in the last paragraph. There's nothing wrong with it; it's just that that syntax is redundant, and can get very lengthy (e.g. $some['big']['long']['variable'] = $some['big']['long']['variable'] && $some['other']['boolean']; ). –  FtDRbwLXw6 Commented Jul 9, 2013 at 16:10
  • You may want to change your examples. Logically, these will always yield the same result = $foo &= false; and $foo &&= false; for $foo = true . So I'm failing to see the problem/goal. –  Jason McCreary Commented Jul 9, 2013 at 16:19
  • 2 @JasonMcCreary: It depends on your definition of "same." As my examples point out, the former yields int(0) and the latter yields bool(false) . So while 0 == false because of implicit type-casting, 0 !== false . –  FtDRbwLXw6 Commented Jul 9, 2013 at 16:50
  • This is still relevent 7 years latter with PHP7/8 type enforcement checks. Very easy to accidentally convert from a bool to an int if you use short syntax. –  evo_rob Commented Apr 6, 2021 at 11:26

3 Answers 3

In a way you have answered your own question:

bitwise operations on 1 and 0 are functionally equivalent to boolean operations on true and false

Bearing in mind that PHP is a weakly typed language, so it is not necessary to typecast to and from strict boolean values as 1 and 0 are equivalent to true and false (except strict equality, see below).

Consider the following code, using your examples:

Given PHP's implicit type juggling , falsy values , and with the exception of strict equaltiy , I'm hard pressed to see where such shorthand operations of &&= and ||= would not yield the same result as &= and |= . Especially when evaluating boolean values . It's likely why such shorthands don't exist in PHP.

Some quick benchmarks prove these are indeed equivalent, except for truthy arrays/objects:

Jason McCreary's user avatar

  • 1 You're correct, but I was actually looking for a solution that didn't change the type (hence why my 3rd example was explicitly type-casting back into a bool ). I have control over both the operands, and they're guaranteed to be bool s, so I'd much rather just use the longer syntax than potentially introduce errors into the code by returning "falsy" values instead of a strict bool like the interface has documented. –  FtDRbwLXw6 Commented Jul 9, 2013 at 17:00
  • 1 Fair. Even though PHP is a weakly typed, dynamic language, I support writing such explicit code. My answer is based on that fact that for boolean values (and most other simple types) bitwise operators are equivalent to boolean operators. But if you want to use such a shorthand, you have to give up strict equality checks (or compare to 0/1). In the end, I don't really see the point. Nonetheless, I wanted to provide an answer for future readers. –  Jason McCreary Commented Jul 9, 2013 at 17:24
  • Keep in mind, you could always cast it before returning the value. Probably good practice anyway. –  Jason McCreary Commented Jul 9, 2013 at 17:45
  • 1 @JasonMcCreary No, boolean and bitwise operators are not equivalent, though their output is. The big difference is, that PHP does not even execute an expression for boolean operates if the outcome makes no difference. So $res = sql_query() OR die(); is not equivalent to $res = sql_query(); $res |= die(); . –  Matteo B. Commented Mar 25, 2015 at 11:45
  • 1 @Matmarbon, correct, in these comments I forgot a key qualifier - functionally equivalent. –  Jason McCreary Commented Mar 25, 2015 at 12:57

As Jason mentioned, bitwise operators will work and it will not be necessary to convert the result back to boolean, as PHP will already handle their value as a boolean properly.

If you want an alternative that does not use bitwise operators, for the sake of readability or if you want strict equality, you can use this method :

Which means, you could change this :

It would also work with multiple conditions :

Dany Caissy's user avatar

  • 2 While helpful, it seems the OP is looking for something native and aware they can write custom code. –  Jason McCreary Commented Jul 9, 2013 at 16:22
  • 1 I don't think there is something native that would do it for them, this is why I put this here. I'll remove my answer if I am proven wrong. While I'm sure OP could have came up with this method by himself, future readers that are less experienced might find it useful. –  Dany Caissy Commented Jul 9, 2013 at 16:23
  • Did someone thing to post this to the PHP dev team? –  theking2 Commented Apr 6, 2022 at 12:00
  • I did: on github –  theking2 Commented Apr 6, 2022 at 12:09

Right, &&= and ||= operators are indeed missing in PHP because bitwise operators can not be used as a replacement (without casting).

Here is an example you would expect to return true but returns false :

The missing &&= operator would return true because 1 && 10 = true

Christopher Pereira's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged php syntax boolean-logic syntactic-sugar or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Upstairs washer suds coming out of basement sink
  • How rich is the richest person in a society satisfying the Pareto principle?
  • Problem about ratio between circumradius and inradius
  • Inductive and projective limit of circles
  • Would an LEO asking for a race constitute entrapment?
  • Current in a circuit is 50% lower than predicted by Kirchhoff's law
  • How do I learn more about rocketry?
  • Transform a list of rules into a list of function definitions
  • Light switch that is flush or recessed (next to fridge door)
  • Why is notation in logic so different from algebra?
  • "It never works" vs "It better work"
  • Word for when someone tries to make others hate each other
  • What was the first "Star Trek" style teleporter in SF?
  • 99 camaro overheating
  • Which weather condition causes the most accidents?
  • In what chapter does Fleur suspect Hagrid?
  • When has the SR-71 been used for civilian purposes?
  • Star Trek: The Next Generation episode that talks about life and death
  • Text wrapping in longtable not working
  • What does 'ex' mean in this context
  • What other marketable uses are there for Starship if Mars colonization falls through?
  • Are all citizens of Saudi Arabia "considered Muslims by the state"?
  • Can Christian Saudi Nationals visit Mecca?
  • Is it a good idea to perform I2C Communication in the ISR?

assignment operators in php 7

PHP Tutorial

  • PHP Tutorial
  • PHP - Introduction
  • PHP - Installation
  • PHP - History
  • PHP - Features
  • PHP - Syntax
  • PHP - Hello World
  • PHP - Comments
  • PHP - Variables
  • PHP - Echo/Print
  • PHP - var_dump
  • PHP - $ and $$ Variables
  • PHP - Constants
  • PHP - Magic Constants
  • PHP - Data Types
  • PHP - Type Casting
  • PHP - Type Juggling
  • PHP - Strings
  • PHP - Boolean
  • PHP - Integers
  • PHP - Files & I/O
  • PHP - Maths Functions
  • PHP - Heredoc & Nowdoc
  • PHP - Compound Types
  • PHP - File Include
  • PHP - Date & Time
  • PHP - Scalar Type Declarations
  • PHP - Return Type Declarations
  • PHP Operators
  • PHP - Operators
  • PHP - Arithmatic Operators
  • PHP - Comparison Operators
  • PHP - Logical Operators
  • PHP - Assignment Operators
  • PHP - String Operators
  • PHP - Array Operators
  • PHP - Conditional Operators
  • PHP - Spread Operator

PHP - Null Coalescing Operator

  • PHP - Spaceship Operator
  • PHP Control Statements
  • PHP - Decision Making
  • PHP - If…Else Statement
  • PHP - Switch Statement
  • PHP - Loop Types
  • PHP - For Loop
  • PHP - Foreach Loop
  • PHP - While Loop
  • PHP - Do…While Loop
  • PHP - Break Statement
  • PHP - Continue Statement
  • PHP - Arrays
  • PHP - Indexed Array
  • PHP - Associative Array
  • PHP - Multidimensional Array
  • PHP - Array Functions
  • PHP - Constant Arrays
  • PHP Functions
  • PHP - Functions
  • PHP - Function Parameters
  • PHP - Call by value
  • PHP - Call by Reference
  • PHP - Default Arguments
  • PHP - Named Arguments
  • PHP - Variable Arguments
  • PHP - Returning Values
  • PHP - Passing Functions
  • PHP - Recursive Functions
  • PHP - Type Hints
  • PHP - Variable Scope
  • PHP - Strict Typing
  • PHP - Anonymous Functions
  • PHP - Arrow Functions
  • PHP - Variable Functions
  • PHP - Local Variables
  • PHP - Global Variables
  • PHP Superglobals
  • PHP - Superglobals
  • PHP - $GLOBALS
  • PHP - $_SERVER
  • PHP - $_REQUEST
  • PHP - $_POST
  • PHP - $_GET
  • PHP - $_FILES
  • PHP - $_ENV
  • PHP - $_COOKIE
  • PHP - $_SESSION
  • PHP File Handling
  • PHP - File Handling
  • PHP - Open File
  • PHP - Read File
  • PHP - Write File
  • PHP - File Existence
  • PHP - Download File
  • PHP - Copy File
  • PHP - Append File
  • PHP - Delete File
  • PHP - Handle CSV File
  • PHP - File Permissions
  • PHP - Create Directory
  • PHP - Listing Files
  • Object Oriented PHP
  • PHP - Object Oriented Programming
  • PHP - Classes and Objects
  • PHP - Constructor and Destructor
  • PHP - Access Modifiers
  • PHP - Inheritance
  • PHP - Class Constants
  • PHP - Abstract Classes
  • PHP - Interfaces
  • PHP - Traits
  • PHP - Static Methods
  • PHP - Static Properties
  • PHP - Namespaces
  • PHP - Object Iteration
  • PHP - Encapsulation
  • PHP - Final Keyword
  • PHP - Overloading
  • PHP - Cloning Objects
  • PHP - Anonymous Classes
  • PHP Web Development
  • PHP - Web Concepts
  • PHP - Form Handling
  • PHP - Form Validation
  • PHP - Form Email/URL
  • PHP - Complete Form
  • PHP - File Inclusion
  • PHP - GET & POST
  • PHP - File Uploading
  • PHP - Cookies
  • PHP - Sessions
  • PHP - Session Options
  • PHP - Sending Emails
  • PHP - Sanitize Input
  • PHP - Post-Redirect-Get (PRG)
  • PHP - Flash Messages
  • PHP - AJAX Introduction
  • PHP - AJAX Search
  • PHP - AJAX XML Parser
  • PHP - AJAX Auto Complete Search
  • PHP - AJAX RSS Feed Example
  • PHP - XML Introduction
  • PHP - Simple XML Parser
  • PHP - SAX Parser Example
  • PHP - DOM Parser Example
  • PHP Login Example
  • PHP - Login Example
  • PHP - Facebook and Paypal Integration
  • PHP - Facebook Login
  • PHP - Paypal Integration
  • PHP - MySQL Login
  • PHP Advanced
  • PHP - MySQL
  • PHP.INI File Configuration
  • PHP - Array Destructuring
  • PHP - Coding Standard
  • PHP - Regular Expression
  • PHP - Error Handling
  • PHP - Try…Catch
  • PHP - Bugs Debugging
  • PHP - For C Developers
  • PHP - For PERL Developers
  • PHP - Frameworks
  • PHP - Core PHP vs Frame Works
  • PHP - Design Patterns
  • PHP - Filters
  • PHP - Callbacks
  • PHP - Exceptions
  • PHP - Special Types
  • PHP - Hashing
  • PHP - Encryption
  • PHP - is_null() Function
  • PHP - System Calls
  • PHP - HTTP Authentication
  • PHP - Swapping Variables
  • PHP - Closure::call()
  • PHP - Filtered unserialize()
  • PHP - IntlChar
  • PHP - CSPRNG
  • PHP - Expectations
  • PHP - Use Statement
  • PHP - Integer Division
  • PHP - Deprecated Features
  • PHP - Removed Extensions & SAPIs
  • PHP - FastCGI Process
  • PHP - PDO Extension
  • PHP - Built-In Functions
  • PHP Useful Resources
  • PHP - Questions & Answers
  • PHP - Quick Guide
  • PHP - Useful Resources
  • PHP - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

The Null Coalescing operator is one of the many new features introduced in PHP 7. The word "coalescing" means uniting many things into one. This operator is used to replace the ternary operation in conjunction with the isset() function.

Ternary Operator in PHP

PHP has a ternary operator represented by the " ? " symbol. The ternary operator compares a Boolean expression and executes the first operand if it is true, otherwise it executes the second operand.

Let us use the ternary operator to check if a certain variable is set or not with the help of the isset() function, which returns true if declared and false if not.

It will produce the following output −

Now, let's remove the declaration of "x" and rerun the code −

The code will now produce the following output −

The Null Coalescing Operator

The Null Coalescing Operator is represented by the "??" symbol. It acts as a convenient shortcut to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

The first operand checks whether a certain variable is null or not (or is set or not). If it is not null, the first operand is returned, else the second operand is returned.

Take a look at the following example −

Now uncomment the first statement that sets $num to 10 and rerun the code −

It will now produce the following output −

A useful application of Null Coalescing operator is while checking whether a username has been provided by the client browser.

The following code reads the name variable from the URL. If indeed there is a value for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the user is called Guest.

Assuming that this script "hello.php" is in the htdocs folder of the PHP server, enter http://localhost/hello.php?name=Amar in the URL, the browser will show the following message −

If http://localhost/hello.php is the URL, the browser will show the following message −

The Null coalescing operator is used as a replacement for the ternary operator’s specific case of checking isset() function. Hence, the following statements give similar results −

You can chain the "??" operators as shown below −

This will set the username to Guest if the variable $name is not set either by GET or by POST method.

IMAGES

  1. Beginner PHP Tutorial

    assignment operators in php 7

  2. PHP operators Tutorial Example

    assignment operators in php 7

  3. Assignment Operators in PHP

    assignment operators in php 7

  4. PHP 7 Essential Guide

    assignment operators in php 7

  5. Assignment Operators in PHP

    assignment operators in php 7

  6. Mastering Assignment Operators in PHP: Examples & In-Depth Explanation

    assignment operators in php 7

VIDEO

  1. Keywords, String, Operators in PHP

  2. php operators, assignment operators

  3. How to Use Operators in PHP

  4. 07

  5. Basic PHP variable and operators

  6. Lecture 10 :- PHP Operators

COMMENTS

  1. PHP: Assignment

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world. ... In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its ...

  2. PHP Assignment Operators

    Use PHP assignment operator (=) to assign a value to a variable. The assignment expression returns the value assigned. Use arithmetic assignment operators to carry arithmetic operations and assign at the same time. Use concatenation assignment operator (.=)to concatenate strings and assign the result to a variable in a single statement.

  3. PHP Operators

    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.

  4. PHP Assignment Operators

    PHP Assignment Operators. PHP assignment operators applied to assign the result of an expression to a variable. = is a fundamental assignment operator in PHP. It means that the left operand gets set to the value of the assignment expression on the right. Operator.

  5. PHP 7 Operators with Example

    PHP 7 Conditional Assignment Operators PHP provides some conditional statements for value assignment of a variable. These conditional assignment operators are used to set a value depending on conditions.

  6. PHP Assignment Operators

    The following table lists out all the assignment operators in PHP programming. Assigns value of 5 to variable x. x += y. Assigns the result of x+y to x. x -= y. Assigns the result of x-y to x. x *= y. Assigns the result of x*y to x. x /= y.

  7. Mastering Assignment Operators in PHP: A Comprehensive Guide

    Recap of key points about assignment operators in PHP. Assignment operators are foundational to PHP programming, allowing developers to initialize, update, and manipulate variables efficiently. From the basic = operator to combined assignment operators like += and .=, understanding their proper use is crucial for writing clear and effective code.

  8. PHP

    PHP - Assignment Operators Examples - You can use assignment operators in PHP to assign values to variables. Assignment operators are shorthand notations to perform arithmetic or other operations while assigning a value to a variable. For instance, the = operator assigns the value on the right-hand side to the variable on the left-han

  9. PHP Assignment Operators: Performing Calculations

    Assignment operators are essential tools for any PHP developer, facilitating calculations and operations on variables while assigning results to other variables in a single statement. Moreover, leveraging assignment operators allows you to make your code more concise, easier to read, and helps in avoiding common programming errors.

  10. Working with PHP Operators

    In this tutorial you will learn how to use PHP operators like arithmetic, assignment, comparison, etc. to manipulate or perform operations on variables and values. ... PHP Spaceship Operator PHP 7. PHP 7 introduces a new spaceship operator (<=>) which can be used for comparing two expressions. It is also known as combined comparison operator.

  11. What is null coalescing assignment ??= operator in PHP 7.4

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  12. PHP: Operators

    Type. 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). Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the ...

  13. PHP Operators

    These operators are nothing but symbols needed to perform operations of various types. Given below are the various groups of operators: Arithmetic Operators. Logical or Relational Operators. Comparison Operators. Conditional or Ternary Operators. Assignment Operators. Spaceship Operators (Introduced in PHP 7)

  14. PHP: Logic

    In addition to what Lawrence said about assigning a default value, one can now use the Null Coalescing Operator (PHP 7). Hence when we want to assign a default value we can write:

  15. PHP assignment operators

    PHP Assignment Operators Last update on August 19 2022 21:50:39 (UTC/GMT +8 hours) Description. Assignment operators allow writing a value to a variable. The first operand must be a variable and the basic assignment operator is "=". The value of an assignment expression is the final value assigned to the variable.

  16. Ternary and Ternary Coalescing Operator in PHP

    Null Coalescing Assignment operator is relatively new in PHP (added in PHP 7.4), so you code might not work in older PHP versions if you decide to use that operator. These operators are syntax sugar only, and do not provide any meaningful performance difference compared to good ol' if/else blocks.

  17. PHP 7.4 : Null Coalescing Assignment Operator

    In PHP 7.0, we got new null coalescing operator (??) which is a syntactic sugar of using isset() for check a value for null. PHP 7.4 has brought new syntactic sugar to assign default value to a variable if it is null.

  18. PHP Operators

    Operators are symbols that instruct the PHP processor to carry out specific actions. For example, the addition (+) symbol instructs PHP to add two variables or values, whereas the greater-than (>) symbol instructs PHP to compare two values.PHP operators are grouped as follows: Arithmetic operators; Assignment operators; Comparison operators; Increment/Decrement operators

  19. PHP: String

    There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.= '), which appends the argument on the right side to the argument on the left side. Please read Assignment Operators for more information.

  20. PHP Null Coalescing Operator

    Summary: in this tutorial, you'll learn about the PHP Null coalescing operator to assign a value to a variable if the variable doesn't exist or null.. Introduction to the PHP null coalescing operator. When working with forms, you often need to check if a variable exists in the $_GET or $_POST by using the ternary operator in conjunction with the isset() construct.

  21. syntax

    Fair. Even though PHP is a weakly typed, dynamic language, I support writing such explicit code. My answer is based on that fact that for boolean values (and most other simple types) bitwise operators are equivalent to boolean operators. But if you want to use such a shorthand, you have to give up strict equality checks (or compare to 0/1).

  22. PHP

    The Null Coalescing operator is one of the many new features introduced in PHP 7. The word "coalescing" means uniting many things into one. This operator is used to replace the ternary operation in conjunction with the isset() function. Ternary Operator in PHP. PHP has a ternary operator represented by the "?" symbol. The ternary operator ...