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 −

Popular Articles

  • Echoing Content Directly (Aug 01, 2024)
  • Sgml Style (Aug 01, 2024)
  • Standard (Xml) Style (Aug 01, 2024)
  • Embedding Php In Web Pages (Aug 01, 2024)
  • Including Code (Aug 01, 2024)

Assignment Operators

Table of Contents

Introduction

Basic assignment operator, combined assignment operators, string and array assignment operators, the role of assignment operators in control structures, best practices and common mistakes.

PHP, a popular server-side scripting language, is fundamental for web development. Understanding how to manipulate data through expressions and operators is crucial for effective PHP programming. Assignment operators are particularly important as they allow you to set and modify the values of variables efficiently. For example, when managing user data in a form submission, assignment operators help store and update the input values seamlessly.

Introduction to assignment operators and their role in PHP

Assignment operators are used to assign values to variables. They come in various forms, each serving a unique purpose. From the basic = operator to more complex ones like += and .=, these operators simplify the process of handling variables and data. They are integral to PHP's functionality, especially in scenarios involving loops, conditional statements, and data manipulation.

The "=" operator

The basic assignment operator in PHP is the "=" sign. It is used to set the value of a variable.

How the basic assignment works in PHP

This operator assigns the value on the right to the variable on the left. It's the foundation of most operations in PHP, allowing values to be initialised and manipulated throughout the script.

Examples of basic assignment

  • Assigning a string to a variable: $name = 'John';
  • Assigning a number to a variable: $age = 30;
  • Assigning the result of an arithmetic operation: $total = 20 + 15;

Overview of combined assignment operators

In PHP, combined assignment operators enhance coding efficiency by performing an operation and an assignment in a single step. These operators are syntactic sugar, reducing the complexity of common tasks in variable manipulation.

Operators and their functions

  • += : Adds and assigns the value. $a = 5; $a += 3; // $a is now 8
  • -= : Subtracts and assigns the value. $b = 5; $b -= 2; // $b is now 3
  • *= : Multiplies and assigns the value. $c = 3; $c *= 4; // $c is now 12
  • /= : Divides the variable by a value and assigns the result. $d = 10; $d /= 2; // $d is now 5
  • %= : Performs division and assigns the remainder to the variable. $e = 10; $e %= 3; // $e is now 1

Real-world examples of using each combined operator

Combined assignment operators are particularly useful in scenarios involving iterative calculations or repeated updates to the same variable, such as calculating running totals or adjusting values in a loop.

  • Using += for summing values in an array: $sum = 0; foreach ($numbers as $number) { $sum += $number; } // Output the sum echo $sum;
  • Using *= in compound interest calculations: $principal = 1500; $rate = 0.05; $years = 10; for ($i = 0; $i < $years; $i++) { $principal *= (1 + $rate); } echo $principal;

Using .= for string concatenation

The .= operator in PHP is a powerful tool for appending one string onto another. This operator simplifies the process of building longer strings from multiple pieces, making it essential for tasks like generating dynamic HTML or processing form inputs.

Using += for array manipulation

While typically used for numerical addition, the += operator also has a significant role in arrays. It adds elements from one array to another but does not overwrite values at existing keys, unlike the array_merge function.

Practical examples demonstrating string and array assignments

  • Building a dynamic URL query: $url = "http://example.com?"; $username = "user"; $token = "abc123"; $url .= "username=" . urlencode($username); $url .= "&token=" . urlencode($token); // Output: http://example.com?username=user&token=abc123

Note: In this example, since the += operator does not overwrite existing keys, the size remains 'medium', as defined in the defaults.

Use in loops (e.g., for, while)

Assignment operators are instrumental within loops for maintaining and updating the loop's control variables. This utility helps in optimizing the code and making it easier to manage and read.

  • Incrementing a counter in a loop: for ($i = 0; $i < 10; $i++) { echo $i . ' '; } // Outputs: 0 1 2 3 4 5 6 7 8 9
  • Accumulating total within a while loop: $i = 0; $total = 0; while ($i < 5) { $total += $i; $i++; } echo $total; // Outputs: 10

Use in conditional statements (if-else)

Assignment operators streamline operations within conditional statements, allowing variables to be updated based on different conditions efficiently.

  • Adjusting values based on conditions: $age = 20; if ($age > 18) { $status = 'adult'; } else { $status = 'minor'; } echo $status; // Outputs: adult
  • Modifying values in an associative array: $scores = ['John' => 75, 'Jane' => 85]; if ($scores['John'] < 80) { $scores['John'] += 5; // Increment John's score } // Outputs: ['John' => 80, 'Jane' => 85]

Example snippets showing assignment operators in control structures

These snippets illustrate how assignment operators facilitate the management of data within PHP's control structures, demonstrating their versatility and efficiency in various programming scenarios.

Assignment operators, while straightforward, require careful use to ensure code clarity and maintainability. Here are some tips to maximize their effectiveness:

  • Always initialize variables before using them with assignment operators to avoid undefined behavior.
  • Use combined assignment operators to make the code more concise and readable, especially within loops and conditional logic.
  • Be mindful of operator precedence to ensure that expressions are evaluated in the order you intend.

Even seasoned developers can fall into traps when using assignment operators. Being aware of these can prevent common errors:

  • Misusing the += operator with non-numeric data types: Remember that += is primarily for numerical calculations. Misapplying it to arrays or strings can lead to unexpected results.
  • Overlooking the return value of an assignment: Assignments in PHP return the assigned value, which can be used in further expressions but sometimes leads to confusing code if not handled carefully.
  • Confusing the == and = operators: It’s easy to mistakenly use = (assignment) instead of == (comparison) in conditional statements, which can lead to assignments where comparisons were intended.

Effective debugging strategies can save hours of troubleshooting. Here are some tailored for assignment operator issues:

  • Check for unintentional assignments within conditional statements — a common source of bugs.
  • Use debugging tools or simple echo statements to trace the changes in variable values throughout your script to understand where values may not be updating as expected.
  • When dealing with complex expressions, break them down and test each component individually to isolate issues.

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.

Encouragement to practice using different types of assignment operators

The best way to master assignment operators is through consistent practice. By integrating these operators into various coding exercises and projects, you can enhance your fluency and confidence in using them. Try creating small scripts that leverage different assignment operators to see how they affect the flow and output of your code.

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

christian.dinh's avatar

Operators are used to perform operations on variables and values.

Arithmetic Operators

PHP has the following basic arithmetic operators to perform common mathematical operations:

Operator Name Description
Addition returns the sum of and
Subtraction returns the difference of and
Multiplication returns the product of and
Division returns the quotient of and
Modulo returns the integer remainder of divided by
Exponentiation returns raised to the power

The division operator returns a float unless its operands are integers and the result is a whole number, in which case it returns an integer.

Operands of modulo are converted to integers before calculating. The modulo result will have the same sign as the dividend.

Assignment Operators

The basic assignment operator is = , which takes the right-hand operand and assigns it to the variable that is the left-hand operand. PHP also has a number of additional assignment operators that are shortcuts for longer expressions.

Arithmetic Assignment Operators

There is an assignment operator for each arithmetic operator above.

Operator Name Description
Addition Assignment is short for
Subtraction Assignment is short for
Multiplication Assignment is short for
Division Assignment is short for
Modulo Assignment is short for
Exponentiation Assignment is short for

Bitwise Assignment Operators

There is an assignment operator for each bitwise operator (see below).

Operator Name Description
And Assignment is short for
Or Assignment is short for
Xor Assignment is short for
Left Shift Assignment is short for
Right Shift Assignment is short for

Bitwise Operators

The bitwise operators manipulate individual bits in an integer.

Operator Name Description
And result has bit set only where both operands have that bit set.
Or result has bit set if either operand has that bit set.
Xor result has bit set only if only one operand has that bit set.
Not takes a single operand and inverts each bit in it.
Left shift means ‘s bits are shifted to the left spaces. zeros are inserted from the right, and the leftmost $b bits are discarded.
Right shift means ‘s bits are shifted to the right spaces. copies of the leftmost bit are inserted from the left, and the rightmost $b bits are discarded.

Comparison Operators

Operator Name Description
Equal is if and are equal after type juggling.
Identical is if and are equal and the same type.
Not Equal is if and are not equal after type juggling.
Not Equal is if and are not equal after type juggling.
Not Identical is if and are not equal or not the same type.
Less Than is if is less than .
Greater Than is if is greater than .
Less Than or Equal to is if is less than or equal to .
Greater Than or Equal to is if is greater than or equal to .
Spaceship returns an integer greater than, less than or equal to zero when is greater than, less than, or equal to respectively.

Incrementing/Decrementing Operators

Operator Name Description
Preincrement Increments by one then returns .
Postincrement Returns , then increments by one.
Predecrement Decrements by one, then returns .
Postdecrement Returns , then decrements by one.

Logical Operators

Operator Name Description
And is only if and are both .
Or is if either or is .
Xor is only when only one of or is .
Not is when $x is and when $x is .
And is only if and are both .
Or is if either or is .

While and and && , and or and || , have the same meaning, they operate at different precedences. Importantly, && and || have higher precedence than = while and and or do not.

String Operators

Operator Name Description
Concatenate Concatenates the left and right operands
Concatenate assignment Concatenates the left and right operands and assigns the value to the left operand.

Array Operators

Operator Name Description
Union returns the union of arrays and .
Union Assignment assigns the union of $x and $y to $x.
Equal is if and consist of the same key/value pairs.
Identical is if and have the same key/value pairs, in the same order, and of the same types.
Not Equal is if and do not have the same key/value pairs.
Not Equal is if and do not have the same key/value pairs.
Not Identical is if is .

When using + with arrays, it returns an array of the right operand appended to the left operand. In cases where there are matching keys in the arrays, the elements from the left operand will be used and the matching elements from the right operand will be discarded.

Type Operators

Operator Name Description
Instance of returns if is an instance of the class .

SomeClass can be a class name, a variable of the given class, or a string containing the class name.

All contributors

StevenSwiniarski's avatar

  • christian.dinh
  • StevenSwiniarski
  • Anonymous contributor

Looking to contribute?

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn PHP on Codecademy

Computer science.

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

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.

  • 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

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

In PHP, operators are symbols that perform operations on one or more values (also known as operands) and return a result. There are several different types of operators in PHP, including:

  • Arithmetic operators : perform basic arithmetic operations.
  • Assignment operators : assign a value to a variable, such as the simple assignment operator.
  • Comparison operators : compare two values and return a boolean result indicating whether the comparison is true or false.
  • Logical operators : perform operations on boolean values and return a boolean result.

Operators are a fundamental building block of programming, and they are used to build expressions and control structures in PHP. Understanding how to use operators correctly is an essential skill for any PHP programmer.

What is an expression?

An expression is any piece of code that produces a value. It's like a small calculation or instruction that does something and gives you a result.

Let's go through some of these operators.

Arithmetic Operators

Arithmetic operators are symbols used to perform basic mathematical operations such as addition, subtraction, multiplication, division, modulo division, and exponentiation. The following are the most common arithmetic operators in PHP:

The addition operator ( + ) adds two values together.

Subtraction

The subtraction operator ( - ) subtracts one value from another.

Multiplication

The multiplication operator ( * ) multiplies two values together.

The division operator ( / ) divides one value by another.

Out of all the arithmetic operators, the modulo operator may feel like one of the strangest operators in PHP. The modulo division operator in PHP is represented by the percent symbol ( % ). It performs modulo division, which returns the remainder of a division operation.

For example, if $a is 5 and $b is 2 , then $a % $b would evaluate to 1 , because 5 divided by 2 is 2 with a remainder of 1 .

The modulo operator is useful in a variety of applications, such as testing for odd or even numbers, determining the last digit of a number, or finding the next multiple of a number. For instance, you can use the modulo operator to test if a number is odd or even by checking if its remainder is 0 or 1 when divided by 2 .

Exponentiation

The exponentiation operator in PHP is represented by two asterisks ( ** ). It calculates the power of a number, with the first operand being the base and the second operand being the exponent.

For example, if $base is 2 and $exponent is 8 , then $base ** $exponent would evaluate to 256 , because 2 raised to the power of 8 is 256 .

The exponentiation operator was introduced in PHP 7.0, so it may not be available in older versions of PHP.

Arithmetic operators are used in PHP to perform simple mathematical operations and are used frequently in many PHP programs. For example, you might use arithmetic operators to calculate the total cost of an order, to determine the average score on a test, or to perform any other type of calculation that involves basic arithmetic operations.

Assignment operators

Assignment operators in PHP are used to assign values to variables. The most commonly used assignment operator is the equal sign ( = ), which assigns the value of the right operand to the left operand. For example:

In this code, the value 5 is assigned to the variable $a .

In addition to the basic assignment operator, there are several compound assignment operators in PHP that combine an operation with an assignment. These operators perform the operation on the values and then assign the result to the variable on the left side. Some of the most commonly used assignment operators in PHP include:

Addition assignment

The addition assignment ( += ) adds the value on the right side to the value of the variable on the left side and then assigns the result back to the left side.

In this example, $a += 5 is the equivalent of $a = $a + 5 .

Subtraction assignment

The subtraction assignment operator ( -= ) subtracts the value on the right side from the value of the variable on the left side, and then assigns the result back to the left side.

In this example, $a -= 2 is the equivalent of $a = $a - 2 .

Multiplication assignment

The multiplication assignment operator ( *= ) multiplies the value of the variable on the left side by the value on the right side, and then assigns the result back to the left side.

In this example, $a *= 5 is the equivalent of $a = $a * 5 .

Division assignment

The division assignment operator ( /= ) divides the value of the variable on the left side by the value on the right side, and then assigns the result back to the left side.

In this example, $a /= 2 is the equivalent of $a = $a / 2 .

Modulo assignment

The modulo assignment operator ( %= ) divides the value of the variable on the left side by the value on the right side and then returns the remainder of the division operation.

In this example, $a %= 5 is the equivalent of $a = $a % 2 .

Exponentiation assignment

The exponentiation assignment operator ( **= ) performs exponentiation and assigns the result to the variable on the left side.

In this example, $a **= 5 is the equivalent of $a = $a ** 5 .

Concatenation assignment

The concatenation assignment operator ( .= ) performs concatenation and assigns the result to the variable on the left side.

In this example, $b .= " world is the equivalent of $b = $a . " world" .

Here's a summary of all the assignment operators.

OperatorExampleEquivalentOperation
Addition
Subtraction
Multiplication
Division
Modulus
Exponentiation
Concatenation

Comparison operators

Comparison operators in PHP are used to compare two values and determine whether a certain condition is true or false . The result of a comparison is a boolean value ( true or false ).

The following are the most common comparison operators in PHP:

The equal to operator ( == ) operator returns true if the values are equal, and false otherwise.

In this example, the $a variable stores true because 5 and 5 are equal to each other. The same isn't true for the $b variable since 5 is not equal to 10 .

Lastly, the third example compares the integer 5 with a string "5" . While they're completely different data types, PHP considers them to be equal. Behind the scenes, PHP changes the data types to be the same before comparing them.

Not equal to

The not equal to operator ( != ) returns true if the values are not equal and false otherwise.

Unlike before, the $a variable will store false even though the numbers are equal to each other. The numbers must not be the same value for a truthy value. On the other hand, the $b variable will store true since that's the case.

Identical to

The identical to operator ( === ) returns true if the values are equal and of the same type , and false otherwise.

The examples are the same as the equal to operator, but there's one difference than before. The $c variable will store false even though the values match. Since their data types are different, PHP has determined that they don't match.

The == (equal to) operator and the === (identical) operator are used to compare values in PHP. The difference between the two is that the == operator performs a loose comparison, while the === operator performs a strict comparison.

You would want to use the == operator over the === operator when you need to compare values of different data types, and you are okay with the type conversion. On the other hand, you would want to use the === operator over the == operator when you need to perform a strict comparison and do not want type conversion.

In general, it's recommended to use the === operator over the == operator when performing comparisons in PHP, as it provides a more secure and accurate comparison.

Not identical to

The not identical to operator ( !== ) returns true if the values are not equal or not of the same type and false otherwise.

Greater than

The greater than operator ( > ) returns true if the left value is greater than the right value and false otherwise.

The less than operator ( < ) returns true if the left value is less than the right value and false otherwise.

Greater than or equal to

The greater than or equal to operator ( >= ) returns true if the left value is greater than or equal to the right value, and false otherwise.

Less than or equal to

The less than or equal to operator ( <= ) returns true if the left value is less than or equal to the right value, and false otherwise.

Here's a table with a summary of all the comparison operators.

OperatorNameDescription
Equal toReturn if both operands are equal; otherwise, it returns .
Not equal toReturn if both operands are equal; otherwise, it returns .
Identical toReturn if both operands have the same data type and equal; otherwise, it returns .
Not identical toReturn if both operands are not equal or not have the same data type; otherwise, it returns .
Greater thanReturn if the operand on the left is greater than the operand on the right; otherwise, it returns .
Greater than or equal toReturn if the operand on the left is greater than or equal to the operand on the right; otherwise, it returns .
Less thanReturn if the operand on the left is less than the operand on the right; otherwise, it returns .
Less than or equal toReturn if the operand on the left is less than or equal to the operand on the right; otherwise, it returns .

Logical Operators

A logical operator in PHP is an operator that performs a logical operation on two or more values and returns a boolean value ( true or false ). The most common logical operators in PHP are && , || , and ! .

Logical operators are useful in PHP because they allow us to make decisions based on multiple conditions, which is an essential part of programming. They help us write more complex and powerful code by allowing us to control the flow of execution based on different conditions.

Let's look at these operators.

The and operator

The and operator ( && ) in PHP is a logical operator that is used to check if two conditions are both true . If both conditions are true , the operator returns true , and if either one or both of the conditions are false, it returns false .

What is a condition?

A condition in PHP is a statement that evaluates to either true or false . Conditions can be created using comparison operators such as == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). Logical operators can be used to combine multiple conditions and make more complex decisions.

In this example, the && operator checks if $age >= 18 and $age <= 65 are both true . If both conditions are true , the $canWork variable will store true .

The && operator is useful because it allows us to write code that makes decisions based on multiple conditions. For example, we could use it to check if someone is eligible for a job based on their age, education, and work experience. By combining multiple conditions with the && operator, we can write more sophisticated and powerful code.

The or operator

The or operator ( || ) in PHP is the logical "or" operator. It is used to combine two conditions and returns true if at least one of the conditions is true .

In this code, the condition $isRaining || $isSnowing is checking if either $isRaining or $isSnowing is true . If either of them is true , the $isWeatherBad variable gets set to true .

The || operator is useful in situations where multiple conditions need to be checked and the program should take action if any of them is true . It allows you to write concise and readable code, as you can check multiple conditions with a single line of code.

The not operator

The ! operator in PHP is the logical "not" operator. It is used to negate or reverse the value of a boolean expression. It returns true if the expression is false , and false if the expression is true .

In this code, the condition !$isRaining is checking if $isRaining is false . If it is false, the $isWeatherGood variable will be set to true . The ! operator is useful in situations where you want to check if a condition is false , or you want to negate the value of a boolean expression.

Short-circuiting

Short-circuiting in PHP refers to a feature of the && operator that stops evaluating its expressions as soon as it can determine the overall result of the operation. For example, consider the following code:

In this code, the condition $debugMode && print("Debugging Code"); checks if the $debugMode variable is true . However, since this variable is false , the second condition is never evaluated. Because we already know the overall result will be false . The PHP interpreter takes advantage of this fact and stops evaluating $b as soon as it knows the result.

What is the print function?

The print function is an alternative solution to the echo keyword. It'll output content onto the page similar to the echo keyword.

If we were to set the $debugMode variable to true , the reverse would occur. Since it's true , the print function gets executed and the message appears on the screen.

Short-circuiting helps to improve the performance of PHP code by avoiding unnecessary calculations and evaluations. In some cases, it can also help to prevent errors or unexpected results by avoiding the evaluation of expressions that would cause errors or have side effects.

Key takeaways

  • Arithmetic operators perform basic arithmetic operations.
  • Assignment operators assign a value to a variable, such as the simple assignment operator.
  • Comparison operators compare two values and return a boolean result indicating whether the comparison is true or false.
  • Logical operators perform operations on boolean values and return a boolean result.

Please read this before commenting

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

Meera Academy

ASP.Net C# Examples

php assignment operators

Php assignment operators.

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

The main assignment operator is “=” , means the right operand value assign to left side operand.

The PHP assignment operators

=      (a=b)                     Means value b assign to value a. +=    (a+=b)   a=a+b      Add and assign -=     (a-=b)    a=a-b       Subtract and assign *=    (a*=b)    a=a*b      Multiply and assign /=     (a/=b)    a=a/b       Divide and assign %=   (a/=b)    a=a%b     Modulus and assign

PHP “=” assignment operator example

<?php $a=5; $b=$a; echo $b; ?>

The output is: 5

In above php example we have variable $a with value 5 and we use “=” operator to assign $a to $b variable.

+=  Add and assign php operator example (a+=b)

<?php $a=5; $b=2; $a+=$b;     // OR  $a=$a+$b echo $a; ?>;

The output is: 7

In above example statement $a+=$b works same as $a=$a+$b.

-= Subtract and assign assignment operator example (a-=b)

<?php $a=5; $b=2; $a-=$b;   // OR $a=$a-$b echo $a; ?>;

The output is: 3

In above example statement $a-=$b is same as $a=$a-$b.

*= Multiply and assign assignment operator example (a*=b)

<?php $a=5; $b=2; $a*=$b;   // OR  $a=$a*$b echo $a; ?>

The output is: 10

In above example statement $a*=$b is same as $a=$a*$b .

/= Divide and assign assignment operator example (a/=b)

<?php $a=10; $b=2; $a/=$b;    // OR  $a=$a/$b echo $a; ?>

In above example statement $a/=$b is same as $a=$a/$b.

%= Modulus and assign assignment operator example (a%=b)

<?php $a=5; $b=2; $a%=$b;  // OR $a=$a%$b echo $a; ?>

The output is: 1

In above example statement $a%=$b is same as $a=$a%$b.

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

PHP Tutorials

  • What is PHP ?
  • PHP Installation using WampServer
  • Run PHP with Wampserver
  • Write PHP Server Code
  • How to Comment Code in PHP ?
  • Echo and Print Statements in PHP
  • What is Variable ?
  • Variable Scope in PHP
  • Arithmetic Operators
  • Logical Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • PHP Conditional Statement
  • IF - ELSE Statement
  • IF - ELSEIF - ELSE Statement
  • PHP Switch Statement
  • PHP Loop Types
  • PHP for loop
  • PHP while loop
  • PHP do-while loop
  • PHP foreach loop
  • PHP Constant
  • PHP Magic Constants
  • PHP Function
  • PHP isset() Function
  • PHP empty() Function
  • PHP String Functions
  • The strlen() string function
  • The substr() string function
  • The str_word_count() string function
  • The strrev() string function
  • The strpos() string function
  • The str_replace() string function
  • The str_repeat() string function
  • The empty() string function
  • The strcmp() string function
  • The trim() string function
  • The strtolower() string function
  • The strtoupper() string function
  • The ucword() string function
  • The ucfirst() string function
  • PHP with HTML Forms
  • PHP GET and POST Methods
  • Form ACTION attribute
  • $_GET, $_POST, $_REQUEST Function
  • What is Session in PHP?
  • PHP session example
  • What is Cookies in PHP?
  • PHP cookies example
  • PHP Date and Time date() function
  • PHP getdate() function
  • PHP file inclue() and require() functions
  • PHP file handling function
  • PHP file open and read fopen(), fread() and fclose() functions
  • PHP file create and write touch() and fwrite() functions
  • PHP fgets(), fgetc() and feof() functions
  • PHP copy(), unlink() and rename() functions
  • PHP file_exists(), filesize() and realpath() functions
  • Directory function in PHP
  • Create directory using mkdir() function
  • Remove directory using rmdir() function
  • Open directory using opendir() function
  • Read directory using readdir() function
  • PHP file upload
  • Upload only image using file upload
  • Change image name while uploading image
  • Create custom file upload in PHP
  • PHP file upload example
  • Types of errors in PHP
  • PHP error handling using die() function
  • PHP Exception handling - try, throw and catch block
  • PHP and MySQL
  • Create database in MySQL Server
  • Create table in MySQL Server
  • PHP - MySQL Database connection
  • Select data from MySQL in PHP
  • Select query in php mysql with example
  • Insert data in mysql using php
  • Update data in mysql using php
  • Delete data from mysql using php

Copyright © 2020 All Rights Reserved - Meera Academy.

  • 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
  • Multiplication Assignment
  • ADVERTISEMENT
  • 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
  • ❯ Simple Assignment

PHP – Simple Assignment Operator

In this tutorial, you shall learn about Simple Assignment Operator, its syntax, and how to use this operator in programs, with examples.

Simple assignment operator is used to assign a value to your variable.

The operator takes two operands, and stores the right operand in the left operand.

The syntax to assign a value or something to a variable using simple assignment operator is

where variable is the left operand and value is the right operand.

1. Assign value to a variable

In the following example, we assign an integer value 10 to a variable $x using simple assignment operator.

PHP Program

PHP - Simple Assignment Operator - Assign value to variable

2. Assign an expression to a variable

We can write an expression and assign it to a variable using simple assignment operator. The expression is first evaluated and then the resulting value is stored in the variable.

In the following example, we assign an expression of adding two numbers to a variable $result .

PHP - Simple Assignment Operator - Assign expression to variable

In this PHP Tutorial , we learned about Simple Assignment Operator , and how to use it to assign a value to a variable.

Popular Courses by TutorialKart

App developement, web development, online tools.

PHP Operators

Php tutorial index.

PHP operators are characters or sets of characters used to manipulate or perform operations on expressions and values.

Operators allow you to perform arithmetic operations, assign values to variables, string concatenation, compare deals, and perform boolean operations.

Types of Operators in PHP

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Ternary Operator
  • Concatenation Operators

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.

  • 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

  • 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
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • Why did Resolve[] fail to verify a statement whose counter-example was proven to be nonexistant by FindInstance[]?
  • Why are these simple equations so slow to `Solve`?
  • Package 'gettext' has no installation candidate, but package exists
  • Is "the above table" more acceptable than "the below table", and if so, why?
  • In "Take [action]. When you do, [effect]", is the action a cost or an instruction?
  • Cutting a 27×27 square into incomparable rectangles
  • How are USB-C cables so thin?
  • Sharing course material from a previous lecturer with a new lecturer
  • Is there a plurality of persons in the being of king Artaxerxes in his use of the pronoun "us" in Ezra 4:18?
  • Is there any point "clean-installing" on a brand-new MacBook?
  • Why does editing '/etc/shells' file using 'sudo open' show an error saying I don't own the file?
  • What's the polarity of this electrolytic capacitor symbol?
  • A burning devil shape rises into the sky like a sun
  • Do space stations have anything that big spacecraft (such as the Space Shuttle and SpaceX Starship) don't have?
  • Isn't an appeal to emotions in fact necessary to validate our ethical decisions?
  • To what extent do value sets determine polynomials mod p?
  • A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
  • Short story in which in which "aliens" from the future appear at a man's door
  • Why is Excel not counting time with COUNTIF?
  • How to Vertically Join Images?
  • As a resident of a Schengen country, do I need to list every visit to other Schengen countries in my travel history in visa applications?
  • Meaning of 折れ込む here
  • What is the soteriological significance of Hebrews 10:1 in the context of God's Redemption Plan?
  • When is internal use internal (considering licenses and their obligations)?

assignment operators in php program

IMAGES

  1. PHP Tutorial For Beginners 16

    assignment operators in php program

  2. PHP operators Tutorial Example

    assignment operators in php program

  3. PHP ASSIGNMENT OPERATORS

    assignment operators in php program

  4. 9

    assignment operators in php program

  5. PHP Assignment Operators

    assignment operators in php program

  6. PHP Assignment Operators

    assignment operators in php program

COMMENTS

  1. PHP: Assignment

    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 value to the result of that expression.

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

  4. PHP Operators

    Learn how to use PHP operators to perform arithmetic, assignment, comparison, logical, and other operations on variables and values. W3Schools provides clear examples, syntax, and exercises for PHP operators.

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

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

  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.

  8. PHP Assignment Operators: Performing Calculations

    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.

  9. PHP

    The basic assignment operator is =, which takes the right-hand operand and assigns it to the variable that is the left-hand operand. PHP also has a number of additional assignment operators that are shortcuts for longer expressions.

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

  11. PHP Assignment Operators

    Assignment operators store the result in same. for eg the addition-assignment operator, represented by the symbol +=, lets you simultaneously add and assign new value .

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

  13. PHP: Operators

    An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). 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 increment ...

  14. PHP Operators

    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.

  15. Operators

    In PHP, operators are symbols that perform operations on one or more values (also known as operands) and return a result. There are several different types of operators in PHP, including: Arithmetic operators: perform basic arithmetic operations. Assignment operators: assign a value to a variable, such as the simple assignment operator.

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

  17. PHP 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.

  18. php assignment operators example

    The PHP assignment operators are used with numeric values to assign value to a variable. The main assignment operator is "=", means the right operand value assign to left side operand.

  19. PHP

    In this tutorial, you shall learn about Simple Assignment Operator, its syntax, and how to use this operator in programs, with examples.

  20. PHP Operators

    Boost your understanding of PHP operators with our comprehensive tutorials. Discover the types of operators in PHP, including arithmetic, assignment, comparison, logical, ternary, and concatenation operators.

  21. PHP Examples

    Learn PHP with hundreds of practical examples and exercises. W3Schools PHP Examples covers all the basic and advanced topics.

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

  23. syntax

    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.