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.

  • 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

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.

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.

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.

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:

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

Quackit Logo

PHP Operators

  • PHP Functions

A quick rundown on the operators available in PHP.

PHP operators are characters (or sets of characters) that perform a special operation within the PHP code. For example, when you use the equals sign ( = ) to assign a value to a variable, you are using an assignment operator. When you add two numbers together using a plus sign ( + ), you are using an arithmetic operator.

Here's a list of the various PHP operators:

Artithmetic Operators

Assignment operator, comparison operators, logical operators, concatenation operators.

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
  • Variable Assignment, Expressions, and Operators

Variables are containers for storing information, such as numbers or text so that they can be used multiple times in the code. Variables in PHP are identified by a dollar sign ($) followed by the variable name. A variable name must begin with a letter or the underscore character and only contain alphanumeric characters and underscores. A variable name cannot contain spaces. Finally, variable names in PHP are case-sensitive.

  • Post author By BrainBell
  • Post date May 12, 2022

assignment operator expression in php

This tutorial covers the following topics:

  • Define a variable
  • Assign a variable by reference
  • Assign a string value to a variable

Assignment Operators

  • Arithmetic Operators (See Comparison Operators and Logical Operators on Conditional Expression Tutorial).

Operator precedence

Expressions, define a variable.

PHP uses the  =  symbol as an assignment operator. The variable goes on the left of the equal sign, and the value goes on the right. Because it assigns a value, the equal sign is called the  assignment operator .

$ variableName = 'Assigned Value' ;

You can break the above example into the following parts:

  • A dollar sign $ prefix
  • Variable name
  • The assignment operator (equal sign = )
  • Assigned value
  • Semicolon to terminate the statement

A PHP variable must be defined before it can be used. Attempting to use an undefined variable will trigger an error exception:

In PHP, you do not need to declare a variable separately before using it. Just assign value to a variable by using the assignment operator (equals sign = ) to make it defined or initialized:

A defined variable can be used by referencing its name, for example, use the print or echo command (followed by the variable’s name) to display the value of the variable on the web page:

Variable names are case-sensitive in PHP, so  $Variable , $variable , $VAriable , and $VARIABLE are all different variables.

Text requires quotes

If you look closely at the PHP code block in the above example, you’ll notice that the value assigned to the second variable isn’t enclosed in quotes. It looks like this:

Then the ‘BrainBell.com’ did use quotes, like this:

The simple rules are as follows:

  • The text requires quotes (single or double)
  • No quotes are required for numbers,  True ,  False  and  Null

Assign a string value to a variable:

Concatenate two strings together to produce “test string”:

Add a string to the end of another to produce “test string”:

Here is a shortcut to adding a string to the end of another:

Assign by reference

By default, PHP assigns all variables other than objects by value and not by reference. PHP has optimizations to make assignment by value faster than assigning by reference, but if you want to assign by reference you can use the  &  operator as follows:

The assignment operator (equal = ) can be combined with other operators to make it easier to write certain expressions. See the following table:

These operators assign values to variables. They start with the assignment operator = and move on to += , -= , etc.(see above table). The operator += adds the value on the right side to the variable on the left:

Arithmetic Operators

Using an operator, you can manipulate the contents of one or more variables or constants to produce a new value. For example, this code uses the addition operator (  +  ) to add the values of  $x  and  $y  together to produce a new value:

So an operator is a symbol that manipulates one or more values, usually producing a new value in the process. The following list describes the types of arithmetic operators:

Sum integers to produce an integer:

The values and variables that are used with an operator are known as operands.

Subtraction, multiplication, and division might have a result that is a float or an integer, depending on the initial value of $var :

Multiply to double a value:

Halve a value:

These work with float types too:

Get the remainder of dividing 5 by 4:

4 exponent (or power) of 2:

These all add 1 to $var:

And these all subtract 1 from $var:

If the  --  or  ++  operator appears before the variable then the interpreter will first evaluate it and then return the changed variable:

If the  --  or  ++  operator appears after the variable then the interpreter will return the variable as it was before the statement run and then increment the variable:

There are many mathematical functions available in the math library of PHP for more complex tasks. We introduce some of these in the next pages.

The precedence of operators in an expression is similar to the precedence defined in any other language. Multiplication and division occur before subtraction and addition, and so on. However, reliance on evaluation orders leads to unreadable, confusing code. Rather than memorize the rules, we recommend you construct unambiguous expressions with parentheses because parentheses have the highest precedence in evaluation.

For example, in the following fragment  $variable  is assigned a value of 32 because of the precedence of multiplication over addition:

The result is much clearer if parentheses are used:

But the following example displays a different result because parentheses have the highest precedence in evaluation.

An expression in PHP is anything that evaluates a value; it is a combination of values, variables, operators, and functions that results in a value. Here are some examples of expressions:

An expression has a value and a type; for example, the expression  4 + 7  has the value  11  and the type  integer,  and the expression "abcdef" has the value  abcdef  and the type  string . PHP automatically converts types when combining values in an expression. For example, the expression 4 + 7.0 contains an integer and a float; in this case, PHP considers the integer as a floating-point number, and the result is a float. The  type conversions  are largely straightforward; however, there are some traps, which are discussed later in this section.

Getting Started with PHP:

  • Introducing PHP
  • PHP Development Environment
  • Delimiting Strings
  • Variable Substitution

assignment operator expression in php

Announcement Bell Icon

Interested in Personalized Training with Job Assistance? Know More

PHP Course For Beginners > Expressions and Operators in PHP

Arithmetic & Assignment Operators in PHP

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

Start a new search

To find content from modules and lessons

What are arithmetic operators in PHP?

What is arithmetic assignment operator, what is the difference between arithmetic and assignment operators, how many arithmetic operators are in php, learner's ratings.

Overall Rating

Ravi Ranjan Tiwari

I am very happy that I am studying from LearnVern.

Muhammad Talha

Prince bavishi, sonakshi raj, shibu kumari, rajiv kumar singh.

It would have been better if you could have provided the resource/source_code files of the CRUD operations so that we could have cross verified our code with yours.

Dravinanshu Mishra

Excellent for Bigners.

Recommended Courses

Card image cap

Advanced PHP with MVC Programming with Practicals

Card image cap

The Complete JavaScript Course - Beginner to Advance

Card image cap

AngularJS Course

Card image cap

CodeIgniter Course

Card image cap

Wordpress Course - Create your own Websites

Card image cap

Web Designing with jQuery

Card image cap

React Js for Web Development

Course content.

Fundamentals of PHP

Introduction to PHP

Understanding sdlc process, how to use learnvern, client server architecture, how to set up php environment.

DBMS And MySQL

What is Data

What is database, what is dbms, sql queries and its types, data types in sql - from 16, sql constraints, create, drop & show database, sql create table, sql insert & select statement, operators in sql, in & not in condition, null & not null condition, clauses in sql, understanding having, distinct & group by, update & delete in sql, alter table command in sql, mysql rename truncate drop, understanding foreign key, mysql joins, mysql views, mysql function, mysql procedure, mysql trigger, normalization, assignment : mysql.

HTTP Protocols in PHP

Understanding HTTP Methods

Basic Syntax in PHP

Understanding PHP Program structure Comments in PHP

Variables in php.

Expressions and Operators in PHP

Comparison & Logical Operators in PHP

Ternary operator in php, assignment : operators.

Superglobal Variables in PHP

Super Global Variable in PHP

Get & post variable in php, $_files & $_env in php, assignment : super global variables.

Conditional Statements in PHP

If-else in PHP

Switch case in php, assignment : conditional statements, functions in php, call by value vs call by reference in php, assignment : functions.

Array In PHP

Array Functions in PHP

Array in php, assignment : array.

String in PHP

String and its Functions in PHP

Assignment : string, loops in php, more examples on loops in php, assignment : loops.

Session and Cookies in PHP

Cookies in PHP

Session in php, header function in php, assignment : header functions.

Date and Time Functions in PHP

Date and Time functions in PHP

Assignment : date time functions.

Include and Require in PHP

Include & Require Statement in PHP

Error handling in php, file upload in php.

Database Connection in PHP

Database Connection in PHP Part 1

Database connection in php part 2, sql injection in php.

CRUD Operation in PHP

Crud - Registration and DB connection Part 1

Crud - registration and db connection part 2, log in operation, read operation, update operation part 1, update operation part 2, log out operation.

MySQL Interview Question

MySQL Interview Question 1

Mysql interview question 2, mysql interview question 3, enjoying this course.

All the Course on LearnVern are Free. So Register/ Signup to have Access all the Course and Videos.

PHP Course For Beginners Code

  • No Certificate
  • Globally Recognized NSDC Certificate

assignment operator expression in php

Share with your Friends

Copy this link and share it with your friends

Refer and win Exciting Gifts

Share learnvern with your friends and earn free rewards and certificates., share a personalized message with your friends..

Your Referred User Count

assignment operator expression in php

assignment operator expression in php

PHP Expressions and Operators

Operators are used to perform operations on variables and values. When we’re talking about operators we’re basically talking about “math”. By operator I mean things like multiplication and division signs.

As you might imagine there are tons of operators. Certainly enough to get lost in. The reality is, a lot of these you won’t use on a regular basis or they’ll make more sense if we cover them in a different lesson.

PHP Operators  can be separated into the following categories:

PHP Arithmetic Operators

Php assignment operators, php incrementing / decrementing operators, php comparison operators, php logical operators.

  • Bitwise Operators

PHP Array Operators

  • PHP String Operators

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

Operator Precedence

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

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

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

Although parentheses are not strictly needed, the readability of the code can often be increased by explicitly grouping rather than by using the implicit predominance and association of the operator.

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

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

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.

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

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

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

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

The PHP logical operators are used to combine conditional statements.

Bitwise Operator In PHP

The detailed illustrations of them are out of these lessons and just we introduce them and their names:

The PHP array operators are used to compare arrays.

String operators in PHP :

PHP has two operators that are specially designed for strings.

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

Related Posts

Learn php variables in detail, php expressions & operators, php switch statement, about the author.

' src=

Nohman Habib

I basically work in the CMS, like Joomla and WordPress and in framework like Laravel and have keen interest in developing mobile apps by utilizing hybrid technology. I also have experience working in AWS technology. In terms of CMS, I give Joomla the most value because I found it so much user freindly and my clients feel so much easy to manage their project in it.

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

Email Address: *

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

ABOUT CODINGACE

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

CEO: codingace.com

Request a Quote

Please complete all required fields!

assignment operator expression in php

  • Language Reference

Expressions

Expressions are the most important building blocks of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type $a = 5 , you're assigning 5 into $a . 5 , obviously, has the value 5, or in other words 5 is an expression with the value of 5 (in this case, 5 is an integer constant).

After this assignment, you'd expect $a 's value to be 5 as well, so if you wrote $b = $a , you'd expect it to behave just as if you wrote $b = 5 . In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function: <?php function foo () { return 5 ; } ?>

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions ), you'd assume that typing $c = foo() is essentially just like writing $c = 5 , and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression ' foo() ' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: int values, floating point values ( float ), string values and bool values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, $a = 5 . It's easy to see that there are two values involved here, the value of the integer constant 5 , and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that $a = 5 , regardless of what it does, is an expression with the value 5. Thus, writing something like $b = ($a = 5) is like writing $a = 5; $b = 5; (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write $b = $a = 5 .

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable-- . These are increment and decrement operators . In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written ++$variable , evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written $variable++ evaluates to the original value of $variable , before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either false or true . PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write $a++ or ++$a . But what if you want to add more than one to it, for instance 3? You could write $a++ multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write $a = $a + 3 . $a + 3 evaluates to the value of $a plus 3, and is assigned back into $a , which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written $a += 3 . This means exactly "take the value of $a , add 3 to it, and assign it back into $a ". In addition to being shorter and clearer, this also results in faster execution. The value of $a += 3 , like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a ). Any two-place operator can be used in this operator-assignment mode, for example $a -= 5 (subtract 5 from the value of $a ), $b *= 7 (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php $first ? $second : $third ?>

If the value of the first subexpression is true (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php function double ( $i ) { return $i * 2 ; } $b = $a = 5 ; /* assign the value five into the variable $a and $b */ $c = $a ++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++ $b ; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double ( $d ++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double (++ $e ); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10 ; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ ?>

Some expressions can be considered as statements. In this case, a statement has the form of ' expr ; ' that is, an expression followed by a semicolon. In $b = $a = 5; , $a = 5 is a valid expression, but it's not a statement by itself. $b = $a = 5; , however, is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means true or false . The constants true and false (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.

Improve This Page

User contributed notes 12 notes.

To Top

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
  • 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. Operators in PHP

    assignment operator expression in php

  2. Operators in PHP

    assignment operator expression in php

  3. PHP ASSIGNMENT OPERATORS

    assignment operator expression in php

  4. PHP Assignment Operators

    assignment operator expression in php

  5. PHP Tutorial For Beginners 16

    assignment operator expression in php

  6. PHP

    assignment operator expression in php

VIDEO

  1. L:17 Expression, Operator Precedence and Operator Associativity

  2. LEC 06 ||while & for ||CHAPTER 4(OPERATOR,EXPRESSION &PYTHON STATEMENTS )||O LEVEL

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

  4. Assignment Operator in PHP in 2024 #webdevelopment #php #webdevelopment #codewithharry #programming

  5. PHP

  6. 09 PHP Tutorial Arithmetic Operators

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

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

  3. PHP Operators

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

  4. PHP Assignment Operators

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

  5. PHP Assignment Operators

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

  6. PHP Assignment Operators: Performing Calculations

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

  7. PHP: Assignment Operators

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

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

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

  10. PHP Operators

    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. ... The precedence of an operator decides which order the operator is evaluated in an expression. PHP ...

  11. Operators

    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. ... In addition to the basic assignment operator, there are several compound assignment operators in PHP that combine an ...

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

  13. PHP Operators

    In PHP, the '=' operator is used for assignment, while the '==' operator is used for loose equality comparison, meaning it checks if two values are equal without considering their data types. ... SASS supports boolean values: true false It is used in conditional compilation where the expression evaluates to either of these values. Assign a ...

  14. PHP: Logic

    Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions ... one can now use the Null Coalescing Operator (PHP 7). Hence when we want to assign a default value we can write: ... In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: "Elvis ...

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

  16. PHP Operators

    PHP Operators. A quick rundown on the operators available in PHP. PHP operators are characters (or sets of characters) that perform a special operation within the PHP code. For example, when you use the equals sign ( = ) to assign a value to a variable, you are using an assignment operator. When you add two numbers together using a plus sign ...

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

  18. Variable Assignment, Expressions, and Operators in PHP

    The assignment operator (equal =) can be combined with other operators to make it easier to write certain expressions. See the following table: Operator Example ... Expressions. An expression in PHP is anything that evaluates a value; it is a combination of values, variables, operators, and functions that results in a value. ...

  19. Learn Arithmetic & Assignment Operators in PHP

    Mathematical calculations are carried out using arithmetic operators. The assignment operators are used to give a property or variable a value. Numeric, date, system, time, and text can all be used as assignment operators. To perform comparisons, comparison operators are needed.

  20. PHP Expressions and Operators

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

  21. PHP: Expressions

    The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements. The last example of expressions we'll deal with here is combined operator-assignment expressions.

  22. syntax

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

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

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