• Language Reference

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of " $a = 3 " is 3. This allows you to do some tricky things: <?php $a = ( $b = 4 ) + 5 ; // $a is equal to 9 now, and $b has been set to 4. ?>

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. For example: <?php $a = 3 ; $a += 5 ; // sets $a to 8, as if we had said: $a = $a + 5; $b = "Hello " ; $b .= "There!" ; // sets $b to "Hello There!", just like $b = $b . "There!"; ?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the " $var = &$othervar; " syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

The above example will output:

More information on references and their potential uses can be found in the References Explained section of the manual.

Arithmetic Assignment Operators

Bitwise assignment operators, other assignment operators.

  • arithmetic operators
  • bitwise operators
  • null coalescing operator

Improve This Page

User contributed notes 4 notes.

To Top

PHP Tutorial

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

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

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

PHP Arithmetic Operators

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

PHP Assignment Operators

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

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

Advertisement

PHP Comparison Operators

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

PHP Increment / Decrement Operators

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

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

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

PHP String Operators

PHP has two operators that are specially designed for strings.

PHP Array Operators

The PHP array operators are used to compare arrays.

PHP Conditional Assignment Operators

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

PHP Exercises

Test yourself with exercises.

Multiply 10 with 5 , and output the result.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

PHP Assignment Operators

Php tutorial index.

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

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

Programming

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

Web & Server

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

PHP Assignment Operators

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

Assignment Operators

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

Assignment Operators Table

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

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

PHP Program

Assignment Operators in PHP

Assignment Operators Tutorials

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

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

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

Popular Courses by TutorialKart

App developement, web development, online tools.

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

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

It will produce the following output −

To Continue Learning Please Login

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:

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:

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

PHP provides the following logical operators:

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

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:

Concatenating Operator

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

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

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

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

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

PHP operators precedence

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

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

However, some operators have higher precedence than others.

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

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

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

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

  • Language Reference

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of " $a = 3 " is 3. This allows you to do some tricky things:

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. For example:

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the " $var = &$othervar; " syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

The new operator returns a reference automatically, as such assigning the result of new by reference is an error.

The above example will output:

More information on references and their potential uses can be found in the References Explained section of the manual.

Arithmetic Assignment Operators

Bitwise assignment operators, other assignment operators.

  • arithmetic operators
  • bitwise operators
  • null coalescing operator
  • PHP - Introduction
  • PHP - Syntax
  • PHP - Comments
  • PHP - Variables
  • PHP - Constants
  • PHP - Data Types
  • PHP - Operators
  • PHP - Echo and Print Statements
  • PHP - Strings
  • PHP - If Else
  • PHP - Switch
  • PHP - While Loop
  • PHP - For Loop
  • PHP - Foreach Loop
  • PHP - goto Statement
  • PHP - Continue Statement
  • PHP - Break Statement
  • PHP - Arrays
  • PHP - Associative Arrays
  • PHP - Sorting Arrays
  • PHP - Functions
  • PHP - Scope of Variables
  • PHP - GET & POST
  • PHP - Predefined Variables
  • PHP - Date & time
  • PHP - Cookies
  • PHP - Classes/Objects
  • PHP - Constructors
  • PHP - Destructors
  • PHP - Encapsulation
  • PHP - Inheritance
  • PHP - Exceptions
  • PHP - Error Handling
  • PHP - Sending Emails
  • PHP & MySQL
  • PHP - Built-In Functions
  • PHP - Data Structures
  • PHP - Examples
  • PHP - Interview Questions

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

PHP - assignment operators example

The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • **= Exponent AND assignment operator
  • %= Modulo AND assignment operator

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

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:

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

PHP Assignment Operators

The assignment operators are used to assign values to variables.

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.

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.

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.

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

PHP String Operators

There are two operators which are specifically designed for strings .

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

PHP Array Operators

The array operators are used to compare arrays:

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:

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

  • Course List
  • Introduction to PHP
  • Environment setup
  • First PHP application
  • Keywords & Identifiers
  • Control structures
  • Conditional: if, else, switch, match, ternary
  • Iteration (loops): do, while, foreach, for
  • Statements: break, continue
  • Intermediate
  • Multi-dimensional arrays
  • Include & Require
  • Form Handling
  • Form Validation
  • State management
  • Sessions & Cookies
  • File handling
  • Object-Oriented Programming
  • OOP: Classes & Objects
  • OOP: $this calling object
  • OOP: Constructors & Destructors
  • OOP: Inheritance
  • OOP: Polymorphism
  • OOP: Composition
  • OOP: Encapsulation - Access Modifiers
  • Error Handling
  • Error & Exception Handling
  • MySQL/MariaDB
  • Connect & Disconnect
  • Create a database
  • Create a database table
  • Insert data
  • Select data
  • Update data
  • Delete data

PHP Operators Tutorial

In this tutorial we learn more about symbols that act as operators in PHP and allow us to perform various operations throughout our application.

These operations include arithmetic, assignment, compound assignment, comparison, logical and more.

What are operators?

  • Array operators
  • Arithmetic operators
  • Assignment operators
  • Conditional assignment operators
  • Comparison operators
  • Incremental operators
  • Logical operators
  • String operators

Operators are symbols that have special meaning in PHP, and they indicate the types of operations that can be done.

As an example, we can consider the + symbol as an operator. It adds whatever number is on the right to the number on the left. This is an operation that is taking place on two operands.

PHP categorizes operators into different types:

Array operators are used to compare arrays. The array operators below may not make any sense at this point, if you are a beginner. We will cover these operators again in the tutorial lesson on arrays.

Arithmetic operators are used with numerical values to perform common mathematical arithmetic.

Assignment operators are used with numerical values to assign a value to a variable.

Conditional assignment operators will set values depending on the outcome of certain conditions. The conditional operators below may not make any sense at this point, if you are a beginner. We will cover them again in the tutorial lesson on conditional control flow.

The null coalescing operator is not available in versions below PHP v7 .

Comparison operators will compare two values against each other and return a true or false boolean value.

The following table lists comparison operators in PHP.

It is important for programmers coming from Javascript to remember that three equal signs === represents evaluating both equal value and equal type, and not just equal value .

Incremental operators are used to increase a value incrementally, and decremental operators are used to decrease a value. These operators are what is known as unary operators and as such only require one operand.

The following table lists incremental and decremental operators in PHP.

In the example above we can see that in both pre and post increments the value is incremented. The choice of which to use is determined by which value we want to work with:

  • If we want to work with the already incremented value, we choose the pre-increment.
  • If we want to work with the value before it is incremented and increment it afterwards, we choose the post-increment.

In most situations it won’t matter because we only want the value to actually increment, and not specifically use the value. We will look into increments and decrements more in the tutorial lesson on looping control flow.

Logical operators are used to combine conditional evaluations. We will work with them again in the tutorial lesson on conditional control flow.

The following table lists logical operators in PHP.

String operators are operators that combine (concatenate) strings together.

The following table lists string operators in PHP.

  • Summary: Points to remember
  • Operators are like keywords that have special meaning in PHP, and indicate operations that can be done.
  • The null coalescing operator ? ? is not available in versions below PHP 7.
  • Javascript programmers should note that === means evaluating both equal value and equal type, and not only equal value.
  • These operators will be used more throughout the tutorial series, and will become much clearer for you.
  • What are data types

Exploring PHP Operators

Throughout this article, we will look at the various types of PHP operators , such as arithmetic operators, assignment operators, comparison operators, and logical operators.

PHP Operators

In order to give you a better understanding of how to implement these operators, we will provide examples of how they are used in practice.

In this way, you can learn how to use them in real scenarios.

  • PHP Operators:
  • PHP Arithmetic Operators:
  • PHP Assignment Operators:
  • PHP Comparison Operators:
  • PHP Increment / Decrement Operators:
  • PHP Logical Operators:
  • PHP String Operators:
  • PHP Array Operators:
  • PHP Conditional Assignment Operators:

PHP Operators

Operators are the fundamental building blocks of any programming language.

PHP offers a number of operators for operating on variables and values.

These include mathematical calculations, comparisons, logical operations, and so on.

Variables and values can be manipulated with the help of operators.

In PHP , the operators are divided into the following categories:

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

PHP Arithmetic Operators

Arithmetic operators in PHP are used for performing common math operations, such as addition, subtraction, multiplication, etc.

PHP Assignment Operators

PHP assignment operators allow you to assign a number to a variable in order to write that value to that variable.

A PHP assignment operator called “ = ” is the most basic assignment operator.

Basically, what this means is that the left operand is assigned the value of the assignment expression on the right side of the equation.

PHP Comparison Operators

A comparison PHP operator compares two values and returns a true or false Boolean value.

Different types of values, such as numbers , strings , and booleans, can be compared using PHP comparison operators.

PHP Increment / Decrement Operators

An increment or decrement operator increases or decreases a variable’s value by 1.

You can use these PHP operators in looping functions and other places where you need to change a variable’s value by a certain amount.

PHP Logical Operators

With logic operators, multiple conditions are combined and evaluated as one Boolean expression.

For creating complex conditional statements, PHP supports a variety of logic operators.

PHP String Operators

In order to manipulate strings in various ways, string operators are used.

In PHP, there are a number of string operators that are supported.

For example, you can concatenate a series of strings, compare a sequence of strings, and search for substrings within a sequence.

PHP Array Operators

An array operator is a method of manipulating an array in a number of different ways.

In order to combine, compare, and modify arrays in a variety of different ways, there are a number of array operators that can be used.

PHP Conditional Assignment Operators

The conditional assignment operator allows a variable to be assigned a value only if a certain condition is met.

A number of conditional assignment operators are available in PHP, which can be used to simplify code and improve its efficiency.

In conclusion, understanding PHP operators is crucial for any developer looking to manipulate variables and values in PHP.

Whether you are working with arithmetic operations, logical operations, string operations, or any other operation, a solid understanding of how these PHP operators work is essential.

By using the examples and explanations provided in this article, you can master the use of PHP operators and improve your PHP programming skills.

With time and practice, you can become proficient in using PHP operators and use them effectively to write more efficient and optimized PHP code.

icon

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.

Feeling bored?

Revitalize and stimulate your mind by solving puzzles in game.

php assignment operators example

Mrexamples 1024 Move Game

trytoprogram c home mobile logo

  • C programming

PHP Basics +

  • PHP Introduction
  • PHP Installation
  • PHP Variables
  • PHP Datatypes
  • PHP Constants
  • PHP Strings

PHP Operators

  • PHP While Loop
  • PHP If Else
  • PHP Functions
  • PHP Math Operations
  • PHP Form Handling

PHP Advanced +

  • PHP Date/Time
  • PHP File Upload
  • PHP File Inclusion
  • PHP Validation
  • PHP File Handling
  • PHP Error Handling
  • PHP Except Handling
  • PHP GET/POST
  • PHP Session
  • PHP Cookies

PHP Mysql Database +

  • MySQL Database
  • MySQL Connect
  • MySQL DB Create
  • MySQL Create Table
  • MySQL Insert Data
  • MySQL Last ID
  • MySQL Prepared Statements
  • MySQL Select
  • MySQL Delete
  • MySQL Update

In this article, you will learn about PHP Operators, different types of operators and how they can be used in PHP programs for different operations.

What are PHP Operators ?

Operators are symbols that tell the  PHP  processor to perform certain actions. The expression 5 – 1 is equal to 4. Here 5 and 1 are called operands and – is called the operator. Operators are used to perform operations on variables and values.

PHP  language supports the following type of operators.

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

Arithmetic Operators

The arithmetic operators are used for arithmetical operations, such as addition, subtraction, multiplication, etc. They take two operands which is why they are called binary operators. Here is the list of arithmetic operators in PHP.

PHP Assignment Operators

The PHP assignment operators are used to write a value to a variable or simply assigning a value to a variable. Here are the assignment PHP operators along with their descriptions.

PHP Comparison Operators

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

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

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable’s value and t he PHP decrement operators are used to decrement a variable’s value. These are called unary operators as they require single operand to operate upon.

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

PHP Logical Operators

The PHP logical operators are used with conditional statements and expressions. So basically conditional operators are used to combine conditional statements.

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

PHP String Operators

PHP has two operators that are specially designed for strings.

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

PHP Array Operators

The PHP array operators are used to compare arrays.

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

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.

Sample usage of Arithmetic Operators:

Assignment Operators

Assignment operators are used to assign values to variables.

Sample usage of Assignment Operators:

Comparison Operators

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

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.

Sample usage of Increment / Decrement Operators:

Logical Operators

Logical operators are typically used to combine conditional statements.

Sample usage of Logical Operators:

String Operators

String operators are specifically designed for strings.

Sample usage of String Operators:

Array Operators

Array operators are used to compare arrays.

Conditional Assignment Operators

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

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

Tutorials Class - Logo

  • PHP Operators

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

Arithmetic operators

Assignment operators.

  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators

PHP Operators with Example

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

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

Run : http://ideone.com/EwZM3b

10 6 16 4 0 64

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

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

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

Run : http://ideone.com/U8sJHv

20 40 20 400 20 0

Comparison Operators

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

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

Increment / Decrement Operators

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

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

Logical Operators

The PHP logical operators are used to combine conditional statements.

  • and And $x and $y True if both $x and $y are true
  • or Or $x or $y True if either $x or $y is true
  • xor Xor $x xor $y True if either $x or $y is true, but not both
  • && And $x && $y True if both $x and $y are true
  • || Or $x || $y True if either $x or $y is true
  • ! Not !$x True if $x is not true

String Operators

PHP has two operators that are specially designed for strings.

  • . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
  • .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

Array Operators

The PHP array operators are used to compare arrays.

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

Share this post:

  • Previous Page
  • PHP Tutorial Index
  • PHP Introduction
  • PHP Terminology
  • PHP Installation
  • PHP Comments
  • PHP Variables
  • PHP Data Types
  • PHP Decision Making
  • PHP Functions
  • PHP Constants
  • PHP Array Functions
  • PHP String Handling
  • PHP Advanced
  • PHP Forms Handling
  • PHP File Upload
  • PHP File Handling
  • PHP Send Mail
  • PHP File Inclusion
  • PHP Date and Time
  • PHP Cookies
  • PHP Session
  • PHP OOP Introduction
  • Objects In PHP
  • PHP MySQL Tutorial
  • PHP : MySQL Database
  • PHP : MySQL Connect
  • PHP : MySQL Create Database
  • PHP : MySQL Create Table
  • PHP : MySQL INSERT Statement
  • PHP : MySQL Select Data
  • PHP : MySQL UPDATE Statement
  • PHP : MySQL DELETE Statement

CodedTag

  • Conditional Operators

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

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

Let’s begin with the ternary operator.

Ternary Operator Syntax

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

Here’s an example:

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

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

The Null Coalescing Operator (??)

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

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

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

The Null Coalescing Assignment Operator (??=)

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

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

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

The Elvis Operator (?:)

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

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

Let’s summarize it.

Wrapping Up

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

Did you find this article helpful?

 width=

Sorry about that. How can we improve it ?

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

Data Format and Types

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

String and Patterns

  • Remove the Last Char

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

PHP Tutorial

  • PHP - Introduction
  • PHP - Advantages & Disadvantages
  • PHP 5 Vs. PHP 7
  • PHP - Syntax
  • PHP - Comments
  • PHP - Keywords
  • PHP - Identifiers
  • PHP - Variables
  • PHP - Variable Scope
  • PHP - $var & $$var
  • PHP - Data Types
  • PHP - echo & print
  • PHP - Strings
  • PHP - Numbers
  • PHP - Maths
  • PHP - Constants
  • PHP - Magic Constants
  • PHP - Operators
  • PHP - Conditional Statements
  • PHP - break & continue
  • PHP - switch Statement
  • PHP - Loops
  • PHP - Conditions & Loops (Mixed)
  • PHP - Functions
  • PHP - Arrays
  • PHP - Multidimensional Associative Array
  • PHP - Global Variables
  • PHP - $GLOBALS
  • PHP - $_SERVER
  • PHP - $_REQUEST
  • PHP - $_POST
  • PHP - $_GET
  • PHP - Double Not Operator
  • PHP - Regular Expressions
  • PHP - Date & Time
  • PHP - Error Handling
  • PHP - Exception Handling
  • PHP - Cookies
  • PHP 7 - Spaceship Operator
  • PHP - CODEIGNITER
  • MVC PHP CodeIgniter Example
  • PHP CodeIgniter - Record Insert & Display

PHP Examples

  • PHP - Examples
  • PHP - Basic Examples
  • PHP - Array Examples
  • PHP - String Examples
  • PHP - Classes & Objects Examples
  • PHP - Exception Handling Examples
  • PHP - JSON Examples
  • PHP - Regular Expressions Examples
  • PHP - Database Examples
  • PHP - File Handling Examples

PHP Practice

  • PHP - Find Output Programs
  • PHP - Aptitude Questions

Home » PHP

PHP Operators (With Examples)

By Shahnail Khan Last updated : December 7, 2023

PHP Operators

Operators are fundamental building blocks of programming languages. They allow us to manipulate and combine data to achieve desired results. In PHP, there are many operators available for various purposes. This tutorial will introduce you to the most common PHP operators and provide examples of their usage.

The following are the operators in PHP:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Increment/Decrement Operators
  • Logical Operators
  • String Operators
  • Array Operators
  • Conditional Assignment Operators

1) PHP Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

The following are the PHP arithmetic operators:

Example of PHP Arithmetic Operators

The output of the above example is:

2) PHP Assignment Operators

Assignment operators are used to assign values to variables.

The following are the PHP assignment operators:

Example of PHP Assignment Operators

3) php comparison operators.

Comparison operators are used to compare two values and return a Boolean ( true / false ) result.

The following are the PHP comparison operators:

Example of PHP Comparison Operators

4) php increment/decrement operators.

Increment and decrement operators are used to increase or decrease the value of a variable by 1.

The following are the PHP increment/decrement operators:

Example of PHP Increment/Decrement Operators

5) php logical operators.

Logical operators are used to combine two or more Boolean values and return a single Boolean result.

The following are the PHP logical operators:

Example of PHP Logical Operators

6) php string operators.

String operators are used to manipulate and combine strings .

The following are the PHP string operators:

Example of PHP String Operators

7) php array operators.

Array operators in PHP are used to compare two arrays, these are basically a kind of relation operators for the array companions.

The following are the PHP array operators:

Example of PHP Array Operators

8) php conditional assignment operators.

Conditional assignment operators are used to define value based on the given conditions.

The following are the PHP conditional assignment operators:

Example of PHP Conditional Assignment Operators

Php operators practice (more examples).

Now let's practice some questions to understand PHP Operators better.

To understand the below-given examples/practices, you should have the knowledge of the following PHP topics:

  • PHP basic syntax
  • PHP data types
  • PHP echo and print statements
  • PHP conditional statements
  • PHP strings

Write a PHP script that calculates the area of a rectangle given its length and width using arithmetic operators.

Create a PHP script that checks if a given number is both divisible by 2 and 3. Use logical operators to perform the check.

Write a PHP function that compares two strings and returns "Equal" if they are the same, "Greater" if the first string is lexicographically greater, and "Smaller" if the second string is lexicographically greater.

Implement a PHP script that determines whether a given number is positive, negative, or zero using the ternary operator.

Develop a PHP program that uses the multiplication and assignment operator (*=) to calculate the square of a number.

Write a PHP function that takes two numbers as parameters and uses the spaceship operator to return:

  • -1 if the first number is less than the second,
  • 0 if they are equal,
  • 1 if the first number is greater than the second.

Create an array of fruits and another array of vegetables. Use array operators to merge these arrays and display the combined list.

Implement a PHP script that uses a loop to print the numbers from 1 to 10 using the post-increment operator.

Write a PHP function that takes two strings as parameters and concatenates them using the concatenation and assignment operator (.=). Return the resulting string.

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

  • What is PHP?
  • Install PHP
  • First PHP Example
  • PHP Variables
  • PHP echo and print
  • PHP Datatypes
  • PHP Constants

PHP Operators

  • PHP if...elseif...else
  • PHP Switch statement
  • PHP While and Do-while Loop
  • PHP For and For-each Loop
  • PHP Functions
  • Introduction to Array
  • PHP Indexed Array
  • PHP Associative Array
  • PHP Multidimensional Array
  • PHP Array Functions
  • PHP Strings
  • PHP String Functions

Form Handling

  • PHP Form Handling
  • Form Handling Example

Session/Cookie

  • Introduction to State Management
  • PHP Cookies
  • PHP Sessions

File Handling

  • Introduction to File Handling
  • Create, Open and Close a File
  • Read data from a File
  • Write and Append data to a File

OOPS Concept

  • Introduction to OOPS Concept
  • Defining a Class
  • Creating Object of a PHP Class
  • Access Modifiers
  • $this keyword in PHP
  • Constructor and Destructor
  • Inheritance & its Type
  • Abstract Class and Methods
  • PHP Interfaces

Error Handling

  • PHP Error Handling
  • PHP Exceptions: try , catch and throw
  • PHP with MySQL

Operators are used to perform operations on PHP variables and simple values.

In PHP there are total 7 types of operators, they are:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Increment/Decrement Operators
  • Logical Operators
  • String Operators
  • Array Operators

There are a few additional operators as well like, Type operator, Bitwise operator, Execution operators etc.

Based on how these operators are used, they are categorised into 3 categories:

  • Unary Operators : Works on a single operand(variable or value).
  • Binary Operators : Works on two operands(variables or values).
  • Ternary Operators : Works on three operands.

PHP Arithmetic Operators

These operators are used to perform basic arithmetic operations like addition, multiplication, division, etc.

PHP Assignment Operators

Assignment operators are used to assign values to variables, either as it is or after performing some arithmetic operation on it. The most basic assignment operator is equal to = .

So basically, the assignment operator provides us with shorthand techniques to perform arithmetic operations.

PHP Comparison Operators

As the name suggest, these are used to compare two values.

PHP Increment/Decrement Operators

These operators are unary operators , i.e they require only one operand.

These operators are very useful and handy when use loops or when we have simply increment any value by one in our program/script.

PHP Logical Operators

Logical operators are generally used when any action depends on two or more conditions.

PHP String Operators

String operators are used to perform operations on string . There are only two string operators, generally PHP built-in functions are used to perform various operations on strings, we will learn about them in coming tutorials.

Here we have a simple example to demonstrate the usage of both the string operators.

studytonight studytonight

PHP Array Operators

These operators are used to compare arrays .

  • ← Prev
  • Next →

  Learn Web Development

  explore mcq tests.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. PHP operators Tutorial Example

    php assignment operators example

  2. PHP operators Tutorial Example

    php assignment operators example

  3. Complete Guide and Tutorials for PHP Operators with example

    php assignment operators example

  4. PHP Assignment Operators with example

    php assignment operators example

  5. 9

    php assignment operators example

  6. Php Operators Comprehensive Guide with Examples

    php assignment operators example

VIDEO

  1. Operators in Python

  2. PHP Assignment/Project 4

  3. PHP operators الدرس الحادي عشر شرح العمليات بالتفصيل

  4. 12th Computer Applications

  5. Java Script Logical Operator Lesson # 08

  6. PHP Comparision Operators in Urdu/Hindi

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.For example:

  2. PHP Operators

    The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. ... Operator Name Example Result Try it == Equal

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

  4. PHP Assignment Operators

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

  5. PHP Assignment Operators

    In this tutorial, you shall learn about Assignment Operators in PHP, different Assignment Operators available in PHP, their symbols, and how to use them in PHP programs, with examples. Assignment Operators. Assignment Operators are used to perform to assign a value or modified value to a variable. Assignment Operators Table. The following table ...

  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. For instance, the = operator assigns the value on the right-hand side to the variable on the left-han

  7. PHP Assignment Operators: Performing Calculations

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

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

  9. PHP

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

  10. PHP: Assignment Operators

    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.For example:

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

  12. PHP assignment operators example

    The example below shows the usage of assignment and compound assignment operators: = Assignment operator += Addition AND assignment operator-= Subtraction AND assignment operator *= Multiply AND assignment operator /= Division AND assignment operator **= Exponent AND assignment operator %= Modulo AND assignment operator

  13. Working with PHP Operators

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

  14. PHP Operators Tutorial

    Conditional assignment operators Conditional assignment operators will set values depending on the outcome of certain conditions. The conditional operators below may not make any sense at this point, if you are a beginner. We will cover them again in the tutorial lesson on conditional control flow. The following table lists conditional ...

  15. Php Operators Comprehensive Guide with Examples

    Exploring PHP Operators. Throughout this article, we will look at the various types of PHP operators, such as arithmetic operators, assignment operators, comparison operators, and logical operators.. In order to give you a better understanding of how to implement these operators, we will provide examples of how they are used in practice.. In this way, you can learn how to use them in real ...

  16. PHP Operators

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

  17. PHP Operators (Explanation and Examples)

    In this article, you will learn about PHP Operators, different types of operators and how they can be used in PHP programs for different operations.. What are PHP Operators?. Operators are symbols that tell the PHP processor to perform certain actions.The expression 5 - 1 is equal to 4. Here 5 and 1 are called operands and - is called the operator.

  18. PHP Assignment Operators With Example-Aimtocode

    Assignment Operators: The PHP assignment operators are used with nemeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. List of Assignment Operators

  19. PHP Operators

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

  20. PHP Operators with Examples

    Assignment operators. The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right. Assignment Same as… Description

  21. PHP Conditional Operator: Examples and Tips

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

  22. PHP Operators (With Examples)

    They allow us to manipulate and combine data to achieve desired results. In PHP, there are many operators available for various purposes. This tutorial will introduce you to the most common PHP operators and provide examples of their usage. The following are the operators in PHP: Arithmetic Operators; Assignment Operators; Comparison Operators

  23. PHP Operators

    In PHP there are total 7 types of operators, they are: Arithmetic Operators. Assignment Operators. Comparison Operators. Increment/Decrement Operators. Logical Operators. String Operators. Array Operators. There are a few additional operators as well like, Type operator, Bitwise operator, Execution operators etc.

  24. Python Operators

    Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.