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 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

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-hand side.

Additionally, there are compound assignment operators like +=, -= , *=, /=, and %= which combine arithmetic operations with assignment. For example, "$x += 5" is a shorthand for "$x = $x + 5", incrementing the value of $x by 5. Assignment operators offer a concise way to update variables based on their current values.

The following table highligts the assignment operators that are supported by PHP −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

The following example shows how you can use these assignment operators in PHP −

It will produce the following output −

  • 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.

php assignment operators

Answered on: Wednesday 24 April, 2024 / Duration: 18 min read

Programming Language: PHP , Popularity : 8/10

Solution 1:

Assignment operators in PHP are used to assign values to variables. They combine the assignment operator "=" with another operator to perform an operation while assigning a value. Here are some examples of assignment operators in PHP:

1. Addition assignment operator (+=): This operator adds the value on the right to the variable on the left and assigns the result to the variable on the left.

2. Subtraction assignment operator (-=): This operator subtracts the value on the right from the variable on the left and assigns the result to the variable on the left.

3. Multiplication assignment operator (*=): This operator multiplies the value on the right with the variable on the left and assigns the result to the variable on the left.

4. Division assignment operator (/=): This operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.

5. Modulus assignment operator (%=): This operator divides the variable on the left by the value on the right and assigns the remainder to the variable on the left.

These assignment operators are useful for performing arithmetic operations while assigning values to variables in PHP.

Solution 2:

Assignment Operators in PHP

1. Assignment Operator (=)

* Assigns a value to a variable.

2. Addition Assignment Operator (+=)

* Adds a value to the existing value of a variable.

3. Subtraction Assignment Operator (-=)

* Subtracts a value from the existing value of a variable.

4. Multiplication Assignment Operator (*=)

* Multiplies the existing value of a variable by a value.

5. Division Assignment Operator (/=)

* Divides the existing value of a variable by a value.

6. Modulus Assignment Operator (%=)

* Computes the remainder of dividing the existing value of a variable by a value.

7. Concatenation Assignment Operator (.=)

* Concatenates a string to the existing value of a variable.

Solution 3:

In PHP, assignment operators are used to assign values to variables. There are several assignment operators available in PHP, which are as follows:

1. Assignment Operator (=): The assignment operator is used to assign a value to a variable.

2. Addition Assignment Operator (+=): The addition assignment operator is used to add a value to a variable and assign the result to the variable.

3. Subtraction Assignment Operator (-=): The subtraction assignment operator is used to subtract a value from a variable and assign the result to the variable.

4. Multiplication Assignment Operator (*=): The multiplication assignment operator is used to multiply a value with a variable and assign the result to the variable.

5. Division Assignment Operator (/=): The division assignment operator is used to divide a variable by a value and assign the result to the variable.

6. Modulus Assignment Operator (%=): The modulus assignment operator is used to find the remainder of a variable divided by a value and assign the result to the variable.

7. Exponent Assignment Operator ( =): The exponent assignment operator is used to raise a variable to the power of a value and assign the result to the variable.

8. Concatenation Assignment Operator (.=): The concatenation assignment operator is used to concatenate a string to a variable and assign the result to the variable.

These are the different assignment operators available in PHP. I hope this helps you with your PHP assignment!

More Articles :

Select in php mysql.

Answered on: Wednesday 24 April, 2024 / Duration: 5-10 min read

Programming Language : PHP , Popularity : 6/10

declare variable in view for loop laravel

Programming Language : PHP , Popularity : 8/10

php csv string to associative array with column name

Without form request validation how can we use this , e: unable to locate package php7.2-mbstring.

Programming Language : PHP , Popularity : 4/10

.env example laravel

Programming Language : PHP , Popularity : 3/10

"codeigniter 4" cart

Programming Language : PHP , Popularity : 10/10

symfony command to check entities

Package phpoffice/phpexcel is abandoned, you should avoid using it. use phpoffice/phpspreadsheet instead., php time format, php remove emoji from string, "message": "call to a member function cannot() on null", "exception": "symfony\\component\\debug\\exception\\fatalthrowableerror",.

Programming Language : PHP , Popularity : 9/10

php code for if $id is not empty, do an action

Convert time to decimal php, "\u00e9" php.

Programming Language : PHP , Popularity : 7/10

->when($min_age, function ($query) use ($min_age){ $mindate = now()->subYears($min_age)->format('Y-m-d'); $query->whereHas('candidate', function ($query) use ($mindate){

Programming Language : PHP , Popularity : 5/10

laravel tinker factory

Not null laravel migration, phpmyadmin delete wordpress shortcode, php change version linux, regex for email php, php get pc cpu gpu, memory etc uses all information example, string to bool php, call php function in js, php pdo rowcount, how to get the current date in php, object of class datetime could not be converted to string, xml to object php, how does substr_compare() works php, php to save txt html.

  • ▼PHP Operators
  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Bitwise Operators
  • String Operators
  • Array Operators
  • Incrementing Decrementing Operators

PHP Assignment Operators

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. In addition to the regular assignment operator "=", several other assignment operators are composites of an operator followed by an equal sign.

Interestingly all five arithmetic operators have corresponding assignment operators, Here is the list.

The following table discussed more details of the said assignment operators.

Shorthand Expression Description
$a+= $b $a = $a + $b Adds 2 numbers and assigns the result to the first.
$a-= $b $a = $a -$b Subtracts 2 numbers and assigns the result to the first.
$a*= $b $a = $a*$b Multiplies 2 numbers and assigns the result to the first.
$a/= $b $a = $a/$b Divides 2 numbers and assigns the result to the first.
$a%= $b $a = $a%$b Computes the modulus of 2 numbers and assigns the result to the first.

View the example in the browser

Previous: Logical Operators Next: Bitwise Operators

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

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
  • 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
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Best Mobile Game Controllers in 2024: Top Picks for iPhone and Android
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Home » PHP Tutorial » PHP Operators

PHP Operators

Summary : in this tutorial, you will learn about PHP operators and how to use them effectively in your script.

An operator takes one or more values, known as operands, and performs a specific operation on them.

For example, the + operator adds two numbers and returns the sum of them.

PHP supports many kinds of operators:

Arithmetic Operators

Assignment operators, bitwise operators, comparison operators.

  • Increment/Decrement Operators

Logical Operators

  • Concatenating Operators

The arithmetic operators require numeric values. If you apply them to non-numeric values, they’ll convert them to numeric values before carrying the arithmetic operation.

The following are the list of arithmetic operators:

OperatorNameDescription
+AdditionReturn the sum of two operands
SubtractionReturn the difference between two operands
*MultiplicationReturn the product of two operands
/DivisionReturn the quotient of two operands
%ModulusReturn the remainder of the division of the first operand by the second one

The following example uses the arithmetic operators:

Comparison operators allow you to compare two operands.

A comparison operator returns a Boolean value, either true or false . If the comparison is truthful, the comparison operator returns true , otherwise, it returns false .

The following are the list of comparison operators in PHP:

OperatorNameDescription
==EqualityReturn if both operands are equal, otherwise returns .
===IdentityReturn if both operands have the same data type and equal, otherwise return .
!===Not identicalReturn if both operands are not equal or not have the same data type, otherwise return .
>Greater thanReturn if the operand on the left  is greater than the operand on the right, otherwise return .
>=Greater than or equal toReturn if the operand on the left  is greater than or equal to the operand on the right, otherwise return .
<Less thanReturn if the operand on the left is less than the operand on the right, otherwise return .
<=Less than or equalReturn if the operand on the left  is less than or equal to the operand on the right, otherwise return .

Logical operators allow you to construct logical expressions. A logical operator returns a Boolean value.

PHP provides the following logical operators:

OperatorNameDescription
&&Logical ANDReturn if both operands are , otherwise return . If the first operand is , it will not evaluate the second operand because it knows for sure that the result is going to be . This is known as short-circuiting.
||Logical ORReturn if one of the operands is , otherwise returns . If the first operand is , it will not evaluate the second one.
xorLogical XORReturn if either operand, not both, is otherwise, return
!Notreturns if the operand is and returns if the operand is .

Bitwise operators perform operations on the binary representation of the operands. The following illustrates bitwise operators in PHP:

OperatorsNameResult
AndIf both bits are 1, the corresponding bit in the result is 1; otherwise, the corresponding bit is 0
Or (inclusive or)If both bits are 0, the corresponding bit in the result is 0; otherwise, the corresponding bit is 1
Xor (exclusive or)If either bit, but not both, in  and  are 1, the corresponding bit in the result is 1; otherwise, the corresponding bit is 0
NotChange bit 1 to 0 and 0 to 1 in the $x operand
Shift leftShifts the bits in left by the number of places specified by .
Shift rightShifts the bits in  right by the number of places specified by .

Incrementing/ Decrementing Operators

Increment (++)  and decrement (–) operators give you a quick way to increase and decrease the value of a variable by 1.

The following table illustrates the increment and decrement operators:

ExampleNameReturned ValueEffect on $a
Pre-increment Increments  by 1, then returns .
Post-increment Returns , then increments  by 1.
Pre-decrement Decrements  by 1, then returns .
Post-decrement Returns , then decrements  by 1.

Concatenating Operator

Concatenating operator (.) allows you to combine two strings into one. It appends the second string to the first one and returns the combined string. For example:

Assignment operator ( = ) assigns a value to a variable and returns a value. The operand on the left is always a variable, while the operand on the right can be a literal value, variable, expression, or a function call that returns a value. For example:

In the first expression, we assigned $x  variable value 10 .  In the second one, we assigned the value of $x to $y variable. The third one is a little bit complicated. First, we assigned 20 to $x . The assignment operator ( = ) returns 20 and then 20 is assigned to $z  variable.

Besides the basic assignment operator( = ), PHP provides you with some assignment operators:

  • plus-equal  +=
  • minus-equal  -=
  • divide-equal  /=
  • multiplication-equal  *=
  • modulus-equal  %=
  • XOR-equal  ^=
  • AND-equal  &=
  • OR-equal  |=
  • concatenate-equal  .=

PHP operators precedence

The precedence of an operator decides which order the operator is evaluated in an expression.

PHP assigned each operator precedence. Some operators have the same precedence, e.g., precedences of the addition ( + ) and subtraction( - ) are equal.

However, some operators have higher precedence than others.

For example, the precedence of the multiplication operator ( * ) is higher than the precedence of the add( + ) and the subtract ( - ) operators:

Because the precedence of the multiplication operator ( * ) is higher than the precedence of the add( + ) operator, PHP evaluates the multiplication operator ( * ) first and then add operator ( * ) second.

To force the evaluation in a particular order, you put the expression inside parentheses () , for example:

In this tutorial, you have briefly learned about the most commonly used PHP operators.

  • 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

PHP Tutorial

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

Syntax explained

PHP Comments

Comments explained

PHP Variables

Variables explained

PHP Echo and Print

Echo and Print explained

PHP Data Types

Data Types explained

PHP Strings

Strings explained

PHP Numbers

Numbers explained

Math explained

PHP Constants

Constants explained

Advertisement

PHP Operators

Operators explained

PHP If...Else and Switch Statements

Conditions explained

PHP While and For Loops

Loops explained

PHP Functions

Functions explained

Arrays explained

PHP Multidimensional Arrays

Multidimensional Arrays explained

PHP Sorting Arrays

Sorting Arrays explained

PHP Superglobals

Superglobals explained

PHP Regular Expressions

Regular Expressions explained

PHP Form Validation

Form Validation explained

PHP Date and Time

Date and Time explained

PHP Include Files

Include Files explained

PHP File Handling

File Handling explained

PHP File Open/Read/Close

File Open/Read/Close explained

PHP Cookies

Cookies explained

PHP Sessions

Sessions explained

PHP Filters

Filters explained

PHP JSON explained

PHP Exceptions

PHP Exceptions explained

PHP Classes/Objects

PHP OOP (Classes/Objects) explained

PHP Select Data From MySQL

Select Data From MySQL explained

PHP SimpleXML Parser

SimpleXML Parser explained

PHP XML Expat Parser

XML Expat Parser explained

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.

CodedTag

  • Conditional Operators

Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions.

In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable.

Let’s begin with the ternary operator.

Ternary Operator Syntax

The Conditional Operator in PHP, also known as the Ternary Operator, assigns values to variables based on a certain condition. It takes three operands: the condition, the value to be assigned if the condition is true, and the value to be assigned if the condition is false.

Here’s an example:

In this example, the condition is $score >= 60 . If this condition is true, the value of $result is “Pass”. Otherwise, the value of $result is “Fail”.

To learn more, visit the PHP ternary operator tutorial . Let’s now explore the section below to delve into the Null Coalescing Operator in PHP.

The Null Coalescing Operator (??)

The Null Coalescing Operator, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

So, In this example, if the $_GET['name'] variable is null, the value of $name is “Guest”. Otherwise, the value of $name is the value of $_GET['name'] .

Here’s another pattern utilizing it with the assignment operator. Let’s proceed.

The Null Coalescing Assignment Operator (??=)

The Null Coalescing Operator with Assignment, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

So, the value of $name is null. The Null Coalescing Assignment Operator assigns the value “Guest” to $name. Therefore, the output of the echo statement is “Welcome,”Guest!”.

Moving into the following section, you’ll learn how to use the Elvis operator in PHP.

The Elvis Operator (?:)

In another hand, The Elvis Operator is a shorthand version of the Ternary Operator. Which assigns a default value to a variable if it is null. It takes two operands: the variable and the default value to be assigned if the variable is null. Here’s an example:

In this example, if the $_GET['name'] variable is null, the value“Guest” $name s “Guest”. Otherwise, the value of $name is the value of $_GET['name'] .

Let’s summarize it.

Wrapping Up

The Conditional Assignment Operators in PHP provide developers with powerful tools to simplify code and make it more readable. You can use these operators to assign values to variables based on certain conditions, assign default values to variables if they are null, and perform shorthand versions of conditional statements. By using these operators, developers can write more efficient and elegant code.

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

  • Facebook -->
  • Twitter -->
  • Linked In -->
  • PHP History
  • Install PHP
  • Hello World
  • PHP Constant
  • Predefined Constants
  • 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 Condition
  • If-else Block
  • Break Statement

PHP Operators

  • Operator Precedence
  • PHP Arithmetic Operators
  • Assignment Operators
  • PHP Bitwise Operators
  • PHP Comparison Operators
  • PHP Increment and Decrement Operator
  • PHP Logical Operators
  • PHP String Operators
  • Array Operators
  • Ternary Operator
  • PHP Enumerable
  • PHP NOT Operator
  • PHP OR Operator
  • PHP Spaceship Operator
  • AND Operator
  • Exclusive OR
  • Spread Operator
  • Elvis Operator
  • Null Coalescing 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

Examples: String and Patterns

  • Remove the Last Char

Other Tutorials

  • require_once & require
  • array_map()
  • 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

  • Size of the functor category
  • How is the integral of a simple function well-defined in Folland?
  • Generate all the free polyominoes who's width and height is no larger than 8
  • Generating function for A261041
  • How does registration work in a modern accordion?
  • Do US universities invite faculty applicants from outside the US for an interview?
  • Basel FRTB Vega Sensitivity for Market Risk Capital Standardised Approach
  • What qualifies as a Cantor diagonal argument?
  • How to go from Asia to America by ferry
  • How to truncate text in latex?
  • How would you read this time change with the given note equivalence?
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?
  • Does death entering into the world through the original sin mean animals were also created eternal?
  • Colossians 1:16 New World Translation renders τα πάντα as “all other things” but why is this is not shown in their Kingdom Interlinear?
  • Setting the desired kernel in GRUB menu
  • Were the common people in Germany ("good germans") morally co-responsible of the war crimes of their government?
  • What is the relationship between language and thought?
  • The question about the existence of an infinite non-trivial controversy
  • How to fold or expand the wingtips on Boeing 777?
  • Integrity concerns
  • What is the translation of this quote by Plato?
  • Approximations for a Fibonacci-Like Sequence
  • How is causality in Laplace transform related to Fourier transform?

assignment operator code in php

COMMENTS

  1. PHP: Assignment

    PHP: Assignment - Manual

  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 Operators - W3Schools ... PHP Operators

  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

    PHP - Assignment Operators Examples

  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

    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. Encouragement to practice using different types of ...

  8. 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.

  9. Master PHP Assignment Operators

    Mastering PHP Assignment Operators: A Guide with Examples Assignment operators are the building blocks of any programming language, and PHP is no exception. These operators allow us to assign values to variables, manipulate existing values, and perform various calculations. In this article, we'll delve into the world of PHP assignment operators ...

  10. php assignment operators

    Assignment operators in PHP are used to assign values to variables. They combine the assignment operator "=" with another operator to perform an operation while assigning a value. Here are some examples of assignment operators in PHP: 1. Addition assignment operator (+=):

  11. Reference assignment operator in PHP, =&

    It's called assignment by reference, which, to quote the manual, "means that both variables end up pointing at the same data, and nothing is copied anywhere". The only thing that is deprecated with =& is "assigning the result of new by reference" in PHP 5 , which might be the source of any confusion.

  12. 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.

  13. PHP: Operators

    Operators - Manual

  14. 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

  15. 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)

  16. Working with PHP Operators

    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.

  17. PHP Operators

    An operator takes one or more values, known as operands, and performs a specific operation on them. For example, the + operator adds two numbers and returns the sum of them. PHP supports many kinds of operators: Arithmetic Operators. Assignment Operators. Bitwise Operators. Comparison Operators.

  18. 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.

  19. PHP Examples

    With our online code editor, you can edit code and view the result in your browser. Videos. ... PHP Operators. ... Modulus (%) Assignment operator: x = y Assignment operator: x += y Assignment operator: x -= y Assignment operator: x *= y Assignment operator: ...

  20. PHP Conditional Operator: Examples and Tips

    Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions. In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable. Let's begin with the ternary operator. Ternary Operator Syntax

  21. Assignment operator as a variable in php

    Assignment operator as a variable in php

  22. php

    I'm using the following code from PHPBuilder.com to handle user privileges on my site: /** * Correct the variables stored in array. ... Reference assignment operator in PHP, =& 5. PHP: function with equality sign as parameter? 45. PHP's =& operator. 3. PHP - assigning values in a function argument - good practice? 1.

  23. 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).