PHP Assignment Operators

Php tutorial index.

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

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

PHP Tutorial

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

PHP - Assignment Operators Examples

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

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

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

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

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

It will produce the following output −

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

PHP Assignment Operators

Description.

Assignment operators allow writing a value to a variable . The first operand must be a variable and the basic assignment operator is "=". The value of an assignment expression is the final value assigned to the variable. In addition to the regular assignment operator "=", several other assignment operators are composites of an operator followed by an equal sign.

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

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

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

View the example in the browser

Previous: Logical Operators Next: Bitwise Operators

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

PHP Language Specification

Expressions.

An expression involves one or more terms and zero or more operators.

A full expression is an expression that is not part of another expression.

A side effect is an action that changes the state of the execution environment. (Examples of such actions are modifying a variable, writing to a device or file, or calling a function that performs such operations).

When an expression is evaluated, it produces a result. It might also produce a side effect. Only a few operators produce side effects. (For example, given the expression statement $v = 10 ; the expression 10 is evaluated to the result 10, and there is no side effect. Then the assignment operator is executed, which results in the side effect of $v being modified. The result of the whole expression is the value of $v after the assignment has taken place. However, that result is never used. Similarly, given the expression statement ++$v ; the expression is evaluated to the result incremented-value-of- $v , and the side effect is that $v is actually incremented. Again, the result is never used).

The occurrence of value computation and side effects is delimited by sequence points , places in a program’s execution at which all the computations and side effects previously promised are complete, and no computations or side effects of future operations have yet begun. There is a sequence point at the end of each full expression. The logical and , logical or , conditional , coalesce and function call operators each contain a sequence point. (For example, in the following series of expression statements, $a = 10; ++$a; $b = $a; , there is sequence point at the end of each full expression, so the assignment to $a is completed before $a is incremented, and the increment is completed before the assignment to $b ).

When an expression contains multiple operators, the precedence of those operators controls the order in which those operators are applied. (For example, the expression $a - $b / $c is evaluated as $a - ($b / $c) because the / operator has higher precedence than the binary - operator). The precedence of an operator is determined by the definition of its associated grammar production.

If an operand occurs between two operators having the same precedence, the order in which the operations are performed is determined by those operators’ associativity . With left-associative operators, operations are performed left-to-right. (For example, $a + $b - $c is evaluated as ($a + $b) - $c ). With right-associative operators, operations are performed right-to-left. (For example, $a = $b = $c is evaluated as $a = ($b = $c) ).

Precedence and associativity can be controlled using grouping parentheses . (For example, in the expression ($a - $b) / $c , the subtraction is done before the division. Without the grouping parentheses, the division would take place first).

While precedence, associativity, and grouping parentheses control the order in which operators are applied, they do not control the order of evaluation of the terms themselves. Unless stated explicitly in this specification, the order in which the operands in an expression are evaluated relative to each other is unspecified. See the discussion above about the operators that contain sequence points. (For example, in the full expression $list1[$i] = $list2[$i++] , whether the value of $i on the left-hand side is the old or new $i , is unspecified. Similarly, in the full expression $j = $i + $i++ , whether the value of $i is the old or new $i , is unspecified. Finally, in the full expression f() + g() * h() , the order in which the three functions are called, is unspecified).

Implementation Notes

An expression that contains no side effects and whose resulting value is not used need not be evaluated. For example, the expression statements 6; , $i + 6; , and $i/$j ; are well formed, but they contain no side effects and their results are not used.

A side effect need not be executed if it can be determined that no other program code relies on its having happened. (For example, in the cases of return $a++; and return ++$a; , it is obvious what value must be returned in each case, but if $a is a variable local to the enclosing function, $a need not actually be incremented.

Primary Expressions

The type and value of parenthesized expression are identical to those of the un-parenthesized expression.

Simple Variable

Constraints

The simple-variable or expression in the last two variants must designate a scalar value or object convertible to string.

A simple-variable expression designates a variable with the name determined by either the variable-name or the string representation of the result of the simple-variable or expression , depending on which case is applicable. In the latter two cases the variable name may contain characters that are not allowed in a lexical variable-name .

The behavior of a simple-variable in different contexts and for different types of variables is as specified in the variables section.

The variable $this is predefined inside any non-static instance method (including constructor) when that method is called from within an object context. The value of $this is the calling object or the object being constructed.

Dereferencable expression

The string-literal must not use variable interpolation and must not be a heredoc or nowdoc string literal.

A dereferencable-expression can be used as the left hand side of dereferencing operators, such as [] , -> and :: . A callable-expression can be used as the left hand side of the function call operator .

A variable is an expression that can in principle be used as an lvalue. However, the individual possible expressions may further restrict whether they can behave as lvalues. An expression that is not a variable can never act as an lvalue.

Constant Access Expression

A constant-access-expression evaluates to the value of the constant with name qualified-name .

A literal evaluates to its value, as specified in the lexical specification for literals .

The names in this series of sections have special meaning and are called intrinsics , but they are not keywords; nor are they functions, they are language constructs that are interpreted by the Engine.

This intrinsic returns TRUE if the variable or value designated by expression is empty, where empty means that the variable designated by it does not exist, or it exists and its value compares equal to FALSE . Otherwise, the intrinsic returns FALSE .

The following values are considered empty: FALSE , 0 , 0.0 , "" (empty string), "0" , NULL , an empty array, and any uninitialized variable.

If this intrinsic is used with an expression that designates a dynamic property , then if the class of that property has an __isset , that method is called. If that method returns TRUE , the value of the property is retrieved (which may call __get if defined) and compared to FALSE as described above. Otherwise, the result is FALSE .

expression must designate a string, or be convertable to a string . The contents of the string must be valid PHP source code. If the source code is ill formed, an exception of type ParseError is thrown.

The PHP source code in the string must not be delimited by opening and closing PHP tags . However, the source code itself may contain the tags.

This intrinsic evaluates the contents of the string designated by expression , as PHP script code.

Execution of a return statement from within the source code terminates the execution, and the value returned becomes the value returned by eval . If the source code is ill formed, eval returns FALSE ; otherwise, eval returns NULL .

The source code is executed in the scope of that from which eval is called.

When expression designates an integer, its value must be in the range 0–254.

exit and die are equivalent.

This intrinsic terminates the current script. If expression designates a string, that string is written to STDOUT . If expression designates an integer, that represents the script’s exit status code . Code 255 is reserved by PHP. Code 0 represents “success”. The exit status code is made available to the execution environment. If expression is omitted or is a string, the exit status code is zero. exit does not have a resulting value.

exit performs the following operations, in order:

  • Writes the optional string to STDOUT .
  • Calls any functions registered via the library function register_shutdown_function in their order of registration.
  • Invokes destructors for all remaining instances.

This intrinsic returns TRUE if all the variables designated by variables s are set and their values are not NULL . Otherwise, it returns FALSE .

If this intrinsic is used with an expression that designate a dynamic property , then if the class of that property has an __isset , that method is called. If that method returns TRUE , the value of the property is retrieved (which may call __get if defined) and if it is not NULL , the result is TRUE . Otherwise, the result is FALSE .

Anonymous Function Creation

This operator returns an object of type Closure , or a derived type thereof, that encapsulates the anonymous function defined within. An anonymous function is defined like, and behaves like, a named function except that the former has no name and has an optional anonymous-function-use-clause .

An expression that designates an anonymous function is compatible with the pseudo-type callable .

The use-variable-name-list is a list of variables from the enclosing scope, which are to be made available by name to the body of the anonymous function. Each of these may be passed by value or byRef, as needed. The values used for these variables are those at the time the Closure object is created, not when it is used to call the function it encapsulates.

An anonymous function defined inside an instance or static method has its scope set to the class it was defined in. Otherwise, an anonymous function is unscoped .

An anonymous function defined inside an instance method is bound to the object on which that method is called, while an an anonymous function defined inside a static method, or prefixed with the optional static modifier is static , and otherwise an anonymous function is unbound .

The new Operator

qualified-name must name a class.

new-variable must be a value of type string that contains the name of a class, or an object.

class-type-designator must not designate an abstract class .

The number of arguments in argument-expression-list must be at least as many as the number of non-optional parameters defined for the class’s constructor .

The new class-type-designator forms create an object of the class type specified by class-type-designator . The new class forms create an object of an anonymous class type , a type that has an unspecified name. In all other respects, however, an anonymous class has the same capabilities as a named class type.

If the class-type-designator is a new-variable resulting in a string value, that string is used as the class name. If the expression results in an object, the class of the object is used as the class for the new object. The new-variable has the same semantics as a variable , but the grammar is restricted to exclude calls.

The qualified-name is resolved according to the rules described in scope resolution operator , including support for self , parent and static .

After the object has been created, each instance property is initialized with the values specified in property definition , or the value NULL if no initializer value is provided.

The object is then initialized by calling the class’s constructor passing it the optional argument-expression-list . If the class has no constructor, the constructor that class inherits (if any) is used. The class can also specify no constructor definition, in this case the constructor call is omitted.

The result of a named-type object-creation-expression is an object of the type specified by class-type-designator . The result of an anonymous class object-creation-expression is an object of unspecified type. However, this type will subtype all types provided by class-base-clause and class-interface-clause and the class-members definition should follow the same inheritance and implementation rules as the regular class declaration does.

Each distinct source code expression of the form new class results in the class type that is different from that of all other anonymous class types. However, multiple evaluations of the same source code expression of the form new class result in instances of the same class type.

Because a constructor call is a function call, the relevant parts of function call operator section also apply.

Array Creation Operator

If array-element-initializer contains &, expression in element-value must designate a variable .

If array-initializer is omitted, the array has zero elements. For convenience, an array-initializer may have a trailing comma; however, this comma is ignored. An array-initializer-list consists of a comma-separated list of one or more array-element-initializer items, each of which is used to provide an element-value and an optional element-key .

If the type of element-key is neither int nor string , keys with float or bool values, or strings whose contents match exactly the pattern of decimal-literal , are converted to integer , and keys of all other types are converted to string .

If element-key is omitted from an array-element-initializer , an element key of type int is associated with the corresponding element-value . The key associated is one more than the largest previously assigned non-negative int key for this array, regardless of whether that key was provided explicitly or by default. If the array has no non-negative int keys, the key 0 is used. If the largest previously assigned int key is the largest integer value that can be represented, the new element is not added.

Once the element keys have been converted to int or string , and omitted element keys have each been associated by default, if two or more array-element-initializer elements in an array-initializer contain the same key, the lexically right-most one is the one whose element-value is used to initialize that element.

The result of this operator is the newly created array value.

If array-element-initializer contains &, element-value’s value is stored using byRef assignment .

Subscript Operator

If dereferencable-expression designates a string, expression must not designate a string.

expression can be omitted only if subscript-expression is used in a modifiable-lvalue context and dereferencable-expression does not designate a string. Exception from this is when dereferencable-expression is an empty string - then it is converted to an empty array.

If subscript-expression is used in a non-lvalue context, the element being designated must exist.

A subscript-expression designates a (possibly non-existent) element of an array or string. When subscript-expression designates an object of a type that implements ArrayAccess , the minimal semantics are defined below; however, they can be augmented by that object’s methods offsetGet and offsetSet .

The element key is designated by expression . If the type of element-key is neither int nor string , keys with float or bool values, or strings whose contents match exactly the pattern of decimal-literal , are converted to integer , and key values of all other types are converted to string .

If both dereferencable-expression and expression designate strings, expression is treated as if it specified the int key zero instead and a non-fatal error is produces.

A subscript-expression designates a modifiable lvalue if and only if dereferencable-expression designates a modifiable lvalue.

dereferencable-expression designates an array

If expression is present, if the designated element exists, the type and value of the result is the type and value of that element; otherwise, the result is NULL .

If expression is omitted, a new element is inserted. Its key has type int and is one more than the highest, previously assigned int key for this array. If this is the first element with an int key, key 0 is used. If the largest previously assigned int key is the largest integer value that can be represented, the new element is not added. The result is the added new element, or NULL if the element was not added.

  • If the usage context is as the left-hand side of a simple-assignment-expression , the value of the new element is the value of the right-hand side of that simple-assignment-expression .
  • If the usage context is as the left-hand side of a compound-assignment-expression : the expression e1 op= e2 is evaluated as e1 = NULL op (e2) .
  • If the usage context is as the operand of a postfix- or prefix-increment or decrement operator , the value of the new element is considered to be NULL .

dereferencable-expression designates a string

The expression is converted to int and the result is the character of the string at the position corresponding to that integer. If the integer is negative, the position is counted backwards from the end of the string. If the position refers to a non-existing offset, the result is an empty string.

If the operator is used as the left-hand side of a simple-assignment-expression ,

  • If the assigned string is empty, or in case of non-existing negative offset (absolute value larger than string length), a warning is raised and no assignment is performed.
  • If the offset is larger than the current string length, the string is extended to a length equal to the offset value, using space (0x20) padding characters.
  • The value being assigned is converted to string and the character in the specified offset is replaced by the first character of the string.

The subscript operator can not be used on a string value in a byRef context or as the operand of the postfix- or prefix-increment or decrement operators or on the left side of compound-assignment-expression , doing so will result in a fatal error.

dereferencable-expression designates an object of a type that implements ArrayAccess

If expression is present,

  • If subscript-expression is used in a non-lvalue context, the object’s method offsetGet is called with an argument of expression . The return value of the offsetGet is the result.
  • If the usage context is as the left-hand side of a simple-assignment-expression , the object’s method offsetSet is called with a first argument of expression and a second argument that is the value of the right-hand side of that simple-assignment-expression . The value of the right-hand side is the result.
  • If the usage context is as the left-hand side of a compound-assignment-expression , the expression e1[e] op= e2 is evaluated as e1[e] = e1->offsetGet(e) op (e2) , which is then processed according to the rules for simple assignment immediately above.
  • If the usage context is as the operand of the postfix- or prefix-increment or decrement operators , the object’s method offsetGet is called with an argument of expression . However, this method has no way of knowing if an increment or decrement operator was used, or whether it was a prefix or postfix operator. In order for the value to be modified by the increment/decrement, offsetGet must return byRef. The result of the subscript operator value returned by offsetGet .

If expression is omitted,

  • If the usage context is as the left-hand side of a simple-assignment-expression , the object’s method offsetSet is called with a first argument of NULL and a second argument that is the value of the right-hand side of that simple-assignment-expression . The type and value of the result is the type and value of the right-hand side of that simple-assignment-expression .
  • If the usage context is as the left-hand side of a compound-assignment-expression : The expression e1[] op= e2 is evaluated as e1[] = e1->offsetGet(NULL) op (e2) , which is then processed according to the rules for simple assignment immediately above.
  • If the usage context is as the operand of the postfix- or prefix-increment or decrement operators , the object’s method offsetGet is called with an argument of NULL . However, this method has no way of knowing if an increment or decrement operator was used, or whether it was a prefix or postfix operator. In order for the value to be modified by the increment/decrement, offsetGet must return byRef. The result of the subscript operator value returned by offsetGet .

Note: The brace ( {...} ) form of this operator has been deprecated.

Function Call Operator

callable-expression must designate a function, by being a value of type string that contains the function’s name, or by being an object of a type that implements __invoke method (including Closure objects).

The number of arguments present in a function call must be at least as many as the number of non-optional parameters defined for that function.

No calls can be made to a conditionally defined function until that function exists.

Any argument that matches a parameter passed byRef should (but need not) designate an lvalue.

If variadic-unpacking is used, the result of the expression must be an array or Traversable . If incompatible value is supplied, the argument is ignored and a non-fatal error is issued.

An expression of the form function-call-expression is a function call . The expression designates the called function , and argument-expression-list specifies the arguments to be passed to that function. An argument can be any value. In a function call, callable-expression is evaluated first, followed by each expression in the order left-to-right. There is a sequence point after each argument is evaluated and right before the function is called. For details of the result of a function call see return statement . The value of a function call is a modifiable lvalue only if the function returns a modifiable value byRef.

When a function is called, the value of each argument passed to it is assigned to the corresponding parameter in that function’s definition, if such a parameter exists. The assignment of argument values to parameters is defined in terms of simple or byRef assignment , depending on how the parameter was declared. There may be more arguments than parameters, in which case, the library functions func_num_args , func_get_arg and func_get_args can be used to get access to the complete argument list that was passed. If the number of arguments present in a function call is fewer than the number of parameters defined for that function, any parameter not having a corresponding argument is considered undefined if it has no default argument value ; otherwise, it is considered defined with that default argument value.

If an undefined variable is passed using byRef, that variable becomes defined, with an initial value of NULL .

Direct and indirect recursive function calls are permitted.

If callable-expression is a string, this is a variable function call .

If variadic-unpacking operation is used, the operand is considered to be a parameter list. The values contained in the operand are fetched one by one (in the same manner as foreach would do) and used for next arguments of for the call. The keys for in the iteration are ignored.

Multiple unpacking operations can be used in the same function call, and unpacking and regular parameters can be mixed in any order.

Member Access Operator

The dereferencable-expression must designate an object or be NULL , FALSE , or an empty string.

expression must be a value of type string (but not a string literal) that contains the name of an instance property ( without the leading $ ) or an instance or static method of that instance’s class type.

A member-access-expression designates an instance property of the object designated by dereferencable-expression with the name given by the string representation of member-name . The value is that of the property, and is a modifiable lvalue if dereferencable-expression is a modifiable lvalue.

When the -> operator is used in a modifiable lvalue context and member-name designate a property that is not visible, the property is treated as a dynamic property . If dereferencable-expression ’s class type defines a __set method , it is called to store the property’s value. When the -> operator is used in a non-lvalue context and member-name designate a property that is not visible, the property is treated as a dynamic property. If dereferencable-expression ’s class type defines a __get method , it is called to retrieve the property’s value.

If dereferencable-expression is NULL , FALSE , or an empty string, an expression of the form $p->x = 10 causes an instance of stdClass to be created with a dynamic property x having a value of 10. $p is then made to refer to this instance.

Member Call Operator

The dereferencable-expression must designate an object.

Additionally the general function call constraints apply.

A member-call-expression calls an instance or static method of the object designated by dereferencable-expression , with the method name given by the string representation of member-name and the arguments given by argument-expression-list . The value of dereferencable-expression is used as the value of $this in the invoked method.

The general function call semantics apply.

If the called method does not exist or is not visible from the current scope an exception is thrown, unless a __call method exists, in which case it will be called instead.

See member access examples .

Postfix Increment and Decrement Operators

The operand of the postfix ++ and – operators must be a modifiable lvalue that has scalar-compatible type.

These operators behave like their prefix counterparts except that the value of a postfix ++ or – expression is the value before any increment or decrement takes place.

Prefix Increment and Decrement Operators

The operand of the prefix ++ or -- operator must be a modifiable lvalue that has scalar-compatible type.

Arithmetic Operands

For a prefix ++ operator used with an arithmetic operand, the side effect of the operator is to increment the value of the operand by 1. The result is the value of the operand after it has been incremented. If an int operand’s value is the largest representable for that type, the operand is incremented as if it were float .

For a prefix -- operator used with an arithmetic operand, the side effect of the operator is to decrement the value of the operand by 1. The result is the value of the operand after it has been decremented. If an int operand’s value is the smallest representable for that type, the operand is decremented as if it were float .

For a prefix ++ or -- operator used with an operand having the value INF , -INF , or NAN , there is no side effect, and the result is the operand’s value.

Boolean Operands

For a prefix ++ or -- operator used with a Boolean-valued operand, there is no side effect, and the result is the operand’s value.

NULL-valued Operands

For a prefix – operator used with a NULL -valued operand, there is no side effect, and the result is the operand’s value. For a prefix ++ operator used with a NULL -valued operand, the side effect is that the operand’s type is changed to int, the operand’s value is set to zero, and that value is incremented by 1. The result is the value of the operand after it has been incremented.

String Operands

For a prefix -- operator used with an operand whose value is an empty string, the side effect is that the operand’s type is changed to int , the operand’s value is set to zero, and that value is decremented by 1. The result is the value of the operand after it has been incremented.

For a prefix ++ operator used with an operand whose value is an empty string, the side effect is that the operand’s value is changed to the string “1”. The type of the operand is unchanged. The result is the new value of the operand.

For a prefix -- or ++ operator used with a numeric string, the numeric string is treated as the corresponding int or float value.

For a prefix -- operator used with a non-numeric string-valued operand, there is no side effect, and the result is the operand’s value.

For a non-numeric string-valued operand that contains only alphanumeric characters, for a prefix ++ operator, the operand is considered to be a representation of a base-36 number (i.e., with digits 0–9 followed by A–Z or a–z) in which letter case is ignored for value purposes. The right-most digit is incremented by 1. For the digits 0–8, that means going to 1–9. For the letters “A”–“Y” (or “a”–“y”), that means going to “B”–“Z” (or “b”–“z”). For the digit 9, the digit becomes 0, and the carry is added to the next left-most digit, and so on. For the digit “Z” (or “z”), the resulting string has an extra digit “A” (or “a”) appended. For example, when incrementing, “a” -> “b”, “Z” -> “AA”, “AA” -> “AB”, “F29” -> “F30”, “FZ9” -> “GA0”, and “ZZ9” -> “AAA0”. A digit position containing a number wraps modulo-10, while a digit position containing a letter wraps modulo-26.

For a non-numeric string-valued operand that contains any non-alphanumeric characters, for a prefix ++ operator, all characters up to and including the right-most non-alphanumeric character is passed through to the resulting string, unchanged. Characters to the right of that right-most non-alphanumeric character are treated like a non-numeric string-valued operand that contains only alphanumeric characters, except that the resulting string will not be extended. Instead, a digit position containing a number wraps modulo-10, while a digit position containing a letter wraps modulo-26.

Object Operands

If the operand has an object type supporting the operation, then the object semantics defines the result. Otherwise, the operation has no effect and the result is the operand.

Shell Command Operator

where ` is the GRAVE ACCENT character 0x60, commonly referred to as a backtick .

This operator passes dq-char-sequence to the command shell for execution, as though it was being passed to the library function shell_exec . If the output from execution of that command is written to STDOUT , that output is the result of this operator as a string. If the output is redirected away from STDOUT , or dq-char-sequence is empty or contains only white space, the result of the operator is NULL .

If shell_exec is disabled, this operator is disabled.

Scope-Resolution Operator

qualified-name must be the name of a class or interface type.

dereferencable-expression must be a value of type string, which contains the name of a class or interface type, or an object.

From inside or outside a class or interface, operator :: allows the selection of a constant. From inside or outside a class, this operator allows the selection of a static property, static method, or instance method. From within a class, it also allows the selection of an overridden property or method.

If the scoped-property-access-expression form is used, this operator is accessing a static property given by simple-variable and can be used as an lvalue.

If the class-constant-access-expression form is used, this operator is is accessing a class constant given by name . This form can not be used as an lvalue.

If the scoped-call-expression form is used, the operator is calling the method given by member-anem , which, outside of the object context, is treated as static method call.

Inside of the object context when $this is defined and the called method is not static and the called class is the same as a parent of the class of $this , then the method call is non-static with the same $this . Otherwise it is a static method call.

relative-scope designates the class with relation to the current class scope. From within a class, self refers to the same class, parent refers to the class the current class extends from. From within a method, static refers to the class corresponds to the class inheritance context in which the method is called. This allows late static binding , when class resolution depends on the dynamic call context.

The value of the form of scope-resolution-expression ending in ::class is a string containing the fully qualified name of the current class, which for a static qualifier, means the current class context.

The clone Operator

primary-expression must designate an object.

The clone operator creates a new object that is a shallow copy of the object designated by primary-expression . Then, if the class type of primary-expression has a method called __clone , it is called to perform a deep copy. The result is the new object.

Consider a class Employee , from which is derived a class Manager . Let us assume that both classes contain properties that are objects. clone is used to make a copy of a Manager object, and behind the scenes, the Manager object uses clone to copy the properties for the base class, Employee .

Exponentiation Operator

The ** operator produces the result of raising the value of the left-hand operand to the power of the right-hand one.

If either of the operands have an object type supporting ** operation, then the object semantics defines the result. The left operand is checked first.

If either or both operands have non-numeric types, their values are converted to type int or float , as appropriate. If both operands have non-negative integer values and the result can be represented as an int , the result has type int ; otherwise, the result has type float . If either or both operands were leading-numeric or non-numeric strings, a non-fatal error must be produced for each.

Unary Operators

These operators associate right-to-left.

Unary Arithmetic Operators

The operand of the unary + and unary - must have scalar-compatible type.

The operand of the unary ~ operator must have arithmetic or string type, or be an object supporting ~ .

For a unary + operator used with an arithmetic operand, the type and value of the result is the type and value of the operand.

For a unary - operator used with an arithmetic operand, the value of the result is the negated value of the operand. However, if an int operand’s original value is the smallest representable for that type , the operand is treated as if it were float and the result will be float .

For a unary ~ operator used with an int operand, the type of the result is int . The value of the result is the bitwise complement of the value of the operand (that is, each bit in the result is set if and only if the corresponding bit in the operand is clear). For a unary ~ operator used with a float operand, the value of the operand is first converted to int before the bitwise complement is computed.

For a unary + operator used with a TRUE -valued operand, the value of the result is 1 and the type is int . When used with a FALSE -valued operand, the value of the result is zero and the type is int .

For a unary - operator used with a TRUE -valued operand, the value of the result is -1 and the type is int . When used with a FALSE -valued operand, the value of the result is zero and the type is int .

For a unary + or unary - operator used with a NULL -valued operand, the value of the result is zero and the type is int .

For a unary + or - operator used with a numeric string or a leading-numeric string, the string is first converted to an int or float , as appropriate, after which it is handled as an arithmetic operand. The trailing non-numeric characters in leading-numeric strings are ignored. With a non-numeric string, the result has type int and value 0. If the string was leading-numeric or non-numeric, a non-fatal error MUST be produced.

For a unary ~ operator used with a string, the result is the string with each byte being bitwise complement of the corresponding byte of the source string.

If the operand has an object type supporting the operation, then the object semantics defines the result. Otherwise, for ~ the fatal error is issued and for + and - the object is converted to int .

Error Control Operator

Operator @ suppresses the reporting of any error messages generated by the evaluation of unary-expression .

If a custom error-handler has been established using the library function set_error_handler , that handler is still called.

On open failure, the value returned by fopen is FALSE , which is sufficient to know to handle the error. The error message that may have been generated by the fopen call is suppressed (not displayed and not logged).

Given the following example:

The following code shows how this statement is handled:

Cast Operator

A cast-type of unset is no longer supported and results in a compile-time error.

With the exception of the cast-type unset and binary (see below), the value of the operand cast-expression is converted to the type specified by cast-type , and that is the type and value of the result. This construct is referred to as a cast and is used as the verb, “to cast”. If no conversion is involved, the type and value of the result are the same as those of cast-expression .

A cast can result in a loss of information.

A cast-type of array results in a conversion to type array .

A cast-type of binary is reserved for future use in dealing with so-called binary strings . For now, it is fully equivalent to string cast.

A cast-type of bool or boolean results in a conversion to type bool .

A cast-type of int or integer results in a conversion to type int .

A cast-type of float , double , or real results in a conversion to type float .

A cast-type of object results in a conversion to type object .

A cast-type of string results in a conversion to type string .

instanceof Operator

Operator instanceof returns TRUE if the value designated by instanceof-subject is an object having the type specified by class-type-designator , is an object whose type is derived from that type, or is an object whose type implements the interface specified by class-type-designator . Otherwise, it returns FALSE .

The type can be specified by class-type-designator in one of the three forms:

  • qualified-name specifies the type name directly.
  • When the new-variable form is used, new-variable may have a string value that contains a class or interface name.
  • Alternatively, new-variable can designate an object, in which case the type of the object is used as the specified type. Note that an interface can not be specified with this form.

Note that instanceof will not invoke autoloader if the name of the type given does not correspond to the existing class or interface, instead it will return FALSE .

Logical NOT Operator

The value of the operand is converted to type bool and if it is TRUE then the result of the operator is FALSE . The result is TRUE otherwise.

Multiplicative Operators

The right-hand operand of operator / and operator % must not be zero.

If either of the operands is an object supporting the operation, the result is defined by that object’s semantics, with the left operand checked first.

The binary * operator produces the product of its operands. If either or both operands have non-numeric types, their values are converted to type int or float , as appropriate. If either or both operands were leading-numeric or non-numeric strings, a non-fatal error MUST be produced for each. Then if either operand has type float , the other is converted to that type, and the result has type float . Otherwise, both operands have type int , in which case, if the resulting value can be represented in type int that is the result type. Otherwise, the result would have type float .

Division by zero results in a non-fatal error. If the value of the numerator is positive, the result value is INF . If the value of the numerator is negative, the result value is -INF . If the value of the numerator is zero, the result value is NAN .

The binary / operator produces the quotient from dividing the left-hand operand by the right-hand one. If either or both operands have non-numeric types, their values are converted to type int or float , as appropriate. If either or both operands were leading-numeric or non-numeric strings, a non-fatal error must be produced for each. Then if either operand has type float , the other is converted to that type, and the result has type float . Otherwise, both operands have type int , in which case, if the mathematical value of the computation can be preserved using type int , that is the result type; otherwise, the type of the result is float .

The binary % operator produces the remainder from dividing the left-hand operand by the right-hand one. If the type of both operands is not int , their values are converted to that type. If either or both operands were leading-numeric or non-numeric strings, a non-fatal error MUST be produced for each. The result has type int . If the right-hand operand has value zero, an exception of type DivisionByZeroError is thrown.

These operators associate left-to-right.

Additive Operators

If either operand of + has array type, the other operand must also have array type.

Binary - operator can not be applied to arrays.

For non-array operands, the binary + operator produces the sum of those operands, while the binary - operator produces the difference of its operands when subtracting the right-hand operand from the left-hand one. If either or both operands have non-array, non-numeric types, their values are converted to type int or float , as appropriate. If either or both operands were leading-numeric or non-numeric strings, a non-fatal error MUST be produced for each. Then if either operand has type float , the other is converted to that type, and the result has type float . Otherwise, both operands have type int , in which case, if the resulting value can be represented in type int that is the result type. Otherwise, the result would have type float .

If both operands have array type, the binary + operator produces a new array that is the union of the two operands. The result is a copy of the left-hand array with elements inserted at its end, in order, for each element in the right-hand array whose key does not already exist in the left-hand array. Any element in the right-hand array whose key exists in the left-hand array is ignored.

The binary . operator creates a string that is the concatenation of the left-hand operand and the right-hand operand, in that order. If either or both operands have types other than string , their values are converted to type string . The result has type string .

Bitwise Shift Operators

Each of the operands must have scalar-compatible type.

Given the expression e1 << e2 , the bits in the value of e1 are shifted left by e2 positions. Bits shifted off the left end are discarded, and zero bits are shifted on from the right end. Given the expression e1 >> e2 , the bits in the value of e1 are shifted right by e2 positions. Bits shifted off the right end are discarded, and the sign bit is propagated from the left end.

If either operand does not have type int , its value is first converted to that type. If either or both operands were leading-numeric or non-numeric strings, a non-fatal error MUST be produced for each.

The type of the result is int , and the value of the result is that after the shifting is complete. The values of e1 and e2 are unchanged.

Left shifts where the shift count is greater than the bit width of the integer type (e.g. 32 or 64) must always result in 0, even if there is no native processor support for this.

Right shifts where the shift count is greater than the bit width of the integer type (e.g. 32 or 64) must always result in 0 when e1 is positive and -1 when e1 is negative, even if there is no native processor support for this.

If the shift count is negative, an exception of type ArithmeticError is thrown.

Relational Operators

Operator <=> represents comparison operator between two expressions, with the result being an integer less than 0 if the expression on the left is less than the expression on the right (i.e. if $a < $b would return TRUE ), as defined below by the semantics of the operator < , integer 0 if those expressions are equal (as defined by the semantics of the == operator) and integer greater than 0 otherwise.

Operator < represents less-than , operator > represents greater-than , operator <= represents less-than-or-equal-to , and operator >= represents greater-than-or-equal-to .

The type of the result is bool .

Note that greater-than semantics is implemented as the reverse of less-than , i.e. $a > $b is the same as $b < $a . This may lead to confusing results if the operands are not well-ordered - such as comparing two objects not having comparison semantics, or comparing arrays.

The following table shows the result for comparison of different types, with the left operand displayed vertically and the right displayed horizontally. The conversions are performed according to type conversion rules .

NULLboolintfloatstringarrayobjectresource
NULL=->->->->-><<
bool<-1<-<-<-<-<-<-
int<-->22<-<3<-
float<-->22<-<3<-
string<-->->->2, 4<32
array<-->>>>53>
object>->333363
resource>->->->2<32
  • = means the result is always “equals”, i.e. strict comparisons are always FALSE and equality comparisons are always TRUE .
  • < means that the left operand is always less than the right operand.
  • > means that the left operand is always greater than the right operand.
  • -> means that the left operand is converted to the type of the right operand.
  • <- means that the right operand is converted to the type of the left operand.
  • A number means one of the cases below:
  • If either operand has type bool , the other operand is converted to that type. The result is the logical comparison of the two operands after conversion, where FALSE is defined to be less than TRUE .
  • If one of the operands has arithmetic type, is a resource, or a numeric string, which can be represented as int or float without loss of precision, the operands are converted to the corresponding arithmetic type, with float taking precedence over int , and resources converting to int . The result is the numerical comparison of the two operands after conversion.
  • If only one operand has object type, if the object has comparison handler, that handler defines the result. Otherwise, if the object can be converted to the other operand’s type, it is converted and the result is used for the comparison. Otherwise, the object compares greater-than any other operand type.
  • If both operands are non-numeric strings, the result is the lexical comparison of the two operands. Specifically, the strings are compared byte-by-byte starting with their first byte. If the two bytes compare equal and there are no more bytes in either string, the strings are equal and the comparison ends; otherwise, if this is the final byte in one string, the shorter string compares less-than the longer string and the comparison ends. If the two bytes compare unequal, the string having the lower-valued byte compares less-than the other string, and the comparison ends. If there are more bytes in the strings, the process is repeated for the next pair of bytes.
  • If both operands have array type, if the arrays have different numbers of elements, the one with the fewer is considered less-than the other one, regardless of the keys and values in each, and the comparison ends. For arrays having the same numbers of elements, the keys from the left operand are considered one by one, if the next key in the left-hand operand exists in the right-hand operand, the corresponding values are compared. If they are unequal, the array containing the lesser value is considered less-than the other one, and the comparison ends; otherwise, the process is repeated with the next element. If the next key in the left-hand operand does not exist in the right-hand operand, the arrays cannot be compared and FALSE is returned. If all the values are equal, then the arrays are considered equal.
  • When comparing two objects, if any of the object types has its own compare semantics, that would define the result, with the left operand taking precedence. Otherwise, if the objects are of different types, the comparison result is FALSE . If the objects are of the same type, the properties of the objects are compares using the array comparison described above.

Equality Operators

Operator == represents value equality , operators != and <> are equivalent and represent value inequality .

For operators == , != , and <> , the operands of different types are converted and compared according to the same rules as in relational operators . Two objects of different types are always not equal.

Operator === represents same type and value equality , or identity , comparison, and operator !== represents the opposite of === . The values are considered identical if they have the same type and compare as equal, with the additional conditions below:

  • When comparing two objects, identity operators check to see if the two operands are the exact same object, not two different objects of the same type and value.
  • Arrays must have the same elements in the same order to be considered identical.
  • Strings are identical if they contain the same characters, unlike value comparison operators no conversions are performed for numeric strings.

Bitwise AND Operator

The result of this operator is the bitwise-AND of the two operands, and the type of that result is int .

However, if both operands are strings, the result is the string composed of the sequence of bytes that are the result of bitwise AND operation performed on the bytes of the operand strings in the matching positions ( result[0] = s1[0] & s2[0] , etc.). If one of the strings is longer than the other, it is cut to the length of the shorter one.

This operator associates left-to-right.

Bitwise Exclusive OR Operator

The result of this operator is the bitwise exclusive-OR of the two operands, and the type of that result is int .

However, if both operands are strings, the result is the string composed of the sequence of bytes that are the result of bitwise XOR operation performed on the bytes of the operand strings in the matching positions ( result[0] = s1[0] ^ s2[0] , etc.). If one of the strings is longer than the other, it is cut to the length of the shorter one.

Bitwise Inclusive OR Operator

The result of this operator is the bitwise inclusive-OR of the two operands, and the type of that result is int .

However, if both operands are strings, the result is the string composed of the sequence of bytes that are the result of bitwise OR operation performed on the bytes of the operand strings in the matching positions ( result[0] = s1[0] | s2[0] , etc.). If one of the strings is shorter than the other, it is extended with zero bytes.

Logical AND Operator (form 1)

Given the expression e1 && e2 , e1 is evaluated first. If e1 converts to bool as FALSE , e2 is not evaluated, and the result has type bool , value FALSE . Otherwise, e2 is evaluated. If e2 converts to bool as FALSE , the result has type bool , value FALSE ; otherwise, it has type bool , value TRUE . There is a sequence point after the evaluation of e1 .

Except for the difference in precedence, operator && has exactly the same semantics as operator and .

Logical Inclusive OR Operator (form 1)

Given the expression e1 || e2 , e1 is evaluated first. If e1 converts to bool as TRUE , e2 is not evaluated, and the result has type bool , value TRUE . Otherwise, e2 is evaluated. If e2 converts to bool as TRUE , the result has type bool , value TRUE ; otherwise, it has type bool , value FALSE . There is a sequence point after the evaluation of e1 .

Coalesce Operator

Given the expression e1 ?? e2 , if e1 is set and not NULL (i.e. TRUE for isset ), then the result is e1 . Otherwise, then and only then is e2 evaluated, and the result becomes the result of the whole expression. There is a sequence point after the evaluation of e1 .

Note that the semantics of ?? is similar to isset so that uninitialized variables will not produce warnings when used in e1 .

This operator associates right-to-left.

Conditional Operator

Semantics Given the expression e1 ? e2 : e3 , e1 is evaluated first and converted to bool if it has another type. If the result is TRUE , then and only then is e2 evaluated, and the result and its type become the result and type of the whole expression. Otherwise, then and only then is e3 evaluated, and the result and its type become the result and type of the whole expression. There is a sequence point after the evaluation of e1 . If e2 is omitted, the result and type of the whole expression is the value and type of e1 (before the conversion to bool ).

Assignment Operators

The left-hand operand of an assignment operator must be a modifiable lvalue.

Simple Assignment

If the location designated by the left-hand operand is a string element, the key must not be a negative-valued int , and the right-hand operand must have type string .

If assignment-expression designates an expression having value type, see assignment for scalar types If assignment-expression designates an expression having handle type, see assignment for object and resource types . If assignment-expression designates an expression having array type, see assignment of array types .

The type and value of the result is the type and value of the left-hand operand after the store (if any [see below]) has taken place. The result is not an lvalue.

If the location designated by the left-hand operand is a non-existent array element, a new element is inserted with the designated key and with a value being that of the right-hand operand.

If the location designated by the left-hand operand is a string element, then if the key is a negative-valued int , there is no side effect. Otherwise, if the key is a non-negative-valued int , the left-most single character from the right-hand operand is stored at the designated location; all other characters in the right-hand operand string are ignored. If the designated location is beyond the end of the destination string, that string is extended to the new length with spaces (0x20) added as padding beyond the old end and before the newly added character. If the right-hand operand is an empty string, the null character \0 (0x00) is stored.

list intrinsic

list-intrinsic must be used as the left-hand operand in a simple-assignment-expression of which the right-hand operand must be an expression that designates an array or object implementing the ArrayAccess interface (called the source array ).

Each variable in list-or-variable must designate a writable variable (called the target variable ).

At least one of the elements of the list-expression-list must be non-empty.

This intrinsic assigns one or more elements of the source array to the target variables. Target variables may be assigned by reference. On success, it will return a copy of the source array. If the source array is not an array or object implementing ArrayAccess no assignments are performed and the return value is NULL .

For unkeyed-list-expression-list , all elements in the source array having keys of type string are ignored. The element having an int key of 0 is assigned to the first target variable, the element having an int key of 1 is assigned to the second target variable, and so on, until all target variables have been assigned. Any other array elements are ignored. If there are fewer source array elements having int keys than there are target variables, the unassigned target variables are set to NULL and a non-fatal error is produced.

For keyed-list-expression-list , each key-variable pair is handled in turn, with the key and variable being separated by the => symbol. The element having the first key, with the key having been converted using the same rules as the subscript operator , is assigned to the frst target variable. This process is repeated for the second => pair, if any, and so on. Any other array elements are ignored. If there is no array element with a given key, the unassigned target variable is set to NULL and a non-fatal error is produced.

The assignments must occur in this order.

Any target variable may be a list, in which case, the corresponding element is expected to be an array.

If the source array elements and the target variables overlap in any way, the behavior is unspecified.

byRef Assignment

The right-hand-side variable must be an lvalue or a call to a function that returns a value byRef.

unary-expression becomes an alias for assignment-expression . If assignment-expression designates an expression having value type, see byRef assignment for scalar types If assignment-expression designates an expression having handle type, see byRef assignment for non-scalar types . If assignment-expression designates an expression having array type, see deferred array copying .

Compound Assignment

Any constraints that apply to the corresponding binary operator apply to the compound-assignment form as well.

The expression e1 op= e2 is equivalent to e1 = e1 op (e2) , except that e1 is evaluated only once.

yield Operator

Any function containing a yield-expression is a generator function . A generator function generates a collection of zero or more key/value pairs where each pair represents the next in some series. For example, a generator might yield random numbers or the series of Fibonacci numbers. When a generator function is called explicitly, it returns an object of type Generator , which implements the interface Iterator . As such, this allows that object to be iterated over using the foreach statement . During each iteration, the Engine calls the generator function implicitly to get the next key/value pair. Then the Engine saves the state of the generator for subsequent key/value pair requests.

The yield operator produces the result NULL unless the method Generator->send was called to provide a result value. This operator has the side effect of generating the next value in the collection.

If the key is omitted from an a yield-expression , an element key of type int is associated with the corresponding value. The key associated is one more than the previously assigned int key for this collection. However, if this is the first element in this collection with an int key, zero is used.

If the value is also omitted, NULL will be used instead.

If the generator function definition declares that it returns byRef, each value in a key/value pair is yielded byRef.

The following applies only to the yield from form:

A generator function (referred to as a delegating generator ) can delegate to another generator function (referred to as a subgenerator ), a Traversable object, or an array, each of which is designated by expression .

Each value yielded by assignment-expression is passed directly to the delegating generator’s caller.

Each value sent to the delegating generator’s send method is passed to the subgenerator’s send method. If assignment-expression is not a generator function, any sent values are ignored.

Exceptions thrown by assignment-expression are propagated up to the delegating generator.

Upon traversable completion, NULL is returned to the delegating generator if the traversable is not a generator. If the traversable is a generator, its return value is sent to the delegating generator as the value of the yield from expression .

An exception of type Error is thrown if assignment-expression evaluates to a generator that previously terminated with an uncaught exception, or it evaluates to something that is neither Traversable nor an array.

Print expression

print-expression value must be convertable to a string . In particular, it should not be an array and if it is an object, it must implement a __toString method .

After converting print-expression ’s value into a string, if necessary, print writes the resulting string to STDOUT . Unlike echo , print can be used in any context allowing an expression. It always returns the value 1.

See also: double quoted strings and heredoc documents , conversion to string .

Logical AND Operator (form 2)

Except for the difference in precedence, operator and has exactly the same semantics as operator && .

Logical Exclusive OR Operator

If either operand does not have type bool , its value is first converted to that type.

Given the expression e1 xor e2 , e1 is evaluated first, then e2 . If either e1 or e2 converted to bool as TRUE , but not both, the result has type bool , value TRUE . Otherwise, the result has type bool , value FALSE . There is a sequence point after the evaluation of e1 .

Logical Inclusive OR Operator (form 2)

Except for the difference in precedence, operator and has exactly the same semantics as operator || .

Script Inclusion Operators

When creating large applications or building component libraries, it is useful to be able to break up the source code into small, manageable pieces each of which performs some specific task, and which can be shared somehow, and tested, maintained, and deployed individually. For example, a programmer might define a series of useful constants and use them in numerous and possibly unrelated applications. Likewise, a set of class definitions can be shared among numerous applications needing to create objects of those types.

An include file is a script that is suitable for inclusion by another script. The script doing the including is the including file , while the one being included is the included file . A script can be an including file and an included file, either, or neither.

Using the series-of-constants example, an include file called Positions.php might define the constants TOP , BOTTOM , LEFT , and RIGHT , in their own namespace , Positions. Using the set-of-classes example, to support two-dimensional geometry applications, an include file called Point.php might define the class Point . An include file called Line.php might define the class Line (where a Line is represented as a pair of Points).An include file, called Circle.php might define the class Circle (where a Circle is represented as a Point for the origin, and a radius).

If a number of the scripts making up an application each use one or more of the Position constants, they can each include the corresponding include file via the include operator . However, most include files behave the same way each time they are included, so it is generally a waste of time including the same include file more than once into the same scope. In the case of the geometry example, any attempt to include the same include file more than once will result in a fatal “attempted class type redefinition” error. However, this can be avoided by using the include_once operator instead.

The require operator is a variant of the include operator, and the require_once operator is a variant of the include_once operator.

It is important to understand that unlike the C/C++ (or similar) preprocessor, script inclusion in PHP is not a text substitution process. That is, the contents of an included file are not treated as if they directly replaced the inclusion operation source in the including file. See examples below for more information.

An inclusion expression can be written to look like a function call; however, that is not the case, even though an included file can return a value to its including file.

The name used to specify an include file may contain an absolute or relative path. In the latter case, an implementation may use the configuration directive include_path to resolve the include file’s location.

As mentioned above, script inclusion in PHP is not a text substitution process (unlike C/C++'s preprocessor and alike). This allows that one can specify namespaces in the included file even though nested namespaces in a single file only are not permitted:

include.php

Moreover, nested classes in a single file are not permitted whereas classes defined in an included file does not result in a nested class (in a conditionally defined class though) - the same applies for nested interfaces or traits:

c-constants can not be defined within a function or method (in contrast to d-constants . As in the other examples above, this is perfectly legal when it happens through a file inclusion in which the constant does not lose its scope. Consider the following example:

In contrast to constants, functions, classes, interfaces and traits, variables defined at the top level of a file might change their meaning (being a global variable) when the corresponding file is included by another file. This is the case when the inclusion happens in a local scope. In this case the variables become local variables of the corresponding scope. Following an example as illustration:

The include Operator

expression must be convertable to a string, which designates a filename.

Operator include results in parsing and executing the designated include file. If the filename is invalid or does not specify a readable file, a non-fatal error is produced.

When an included file is opened, parsing begins in HTML mode at the beginning of the file. After the included file has been parsed, it is immediately executed.

Variables defined in an included file take on scope of the source line on which the inclusion occurs in the including file. However, functions and classes defined in the included file are always in global scope.

If inclusion occurs inside a function definition within the including file, the complete contents of the included file are treated as though it were defined inside that function.

The result produced by this operator is one of the following:

  • If the included file returned any value , that value is the result.
  • If the included file has not returned any value, the result is the integer 1 .
  • If the inclusion failed for any reason, the result is FALSE .

The library function get_included_files provides the names of all files included by any of the four including operators.

The include_once Operator

This operator is identical to operator include except that in the case of include_once , the same include file is included once per program execution.

Once an include file has been included, a subsequent use of include_once on that include file results in a return value of TRUE but nothing else happens.

The files are identified by the full pathname, so different forms of the filename (such as full and relative path) still are considered the same file.

The require Operator

This operator is identical to operator include except that in the case of require , failure to find/open the designated include file produces a fatal error.

The require_once Operator

This operator is identical to operator require except that in the case of require_once , the include file is included once per program execution.

Once an include file has been included, a subsequent use of require_once on that include file results in a return value of TRUE but nothing else happens.

Constant Expressions

The expression may only use the following syntactic elements:

  • Literals . String literals must not use interpolation.
  • Array creation expressions .
  • Unary operators + , - , ~ , ! .
  • Binary operators + , - , * , / , % , . , ** , ^ , | , & , < , > , <= , >= , <=> , == , != , === , !== , && , || , ?? .
  • Conditional expressions .
  • Subscript expressions .
  • Constant access expressions .
  • Class constant access expressions .

A constant-expression evaluates to the value of the constituent expression .

  • 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

php assignment expression

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:

OperatorExampleSame as
=$a = 2;
+=$a += 2;$a = $a + 2;
-=$a -= 2;$a = $a – 2;
/=$a /= 2;$a = $a / 2;
%=$a %= 2;$a = $a % 2;
.=$a .= $b;$a = $a . $b;
*=$a *= 2;$a = $a * 2;

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:

OperatorDescription
sum or addition
subtraction
division
multiplication
modulus
exponentiation (PHP 5.6 and above)
add 1
subtract 1

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

Home » PHP Tutorial » PHP Operators

PHP Operators

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

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

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

PHP supports many kinds of operators:

Arithmetic Operators

Assignment operators, bitwise operators, comparison operators.

  • Increment/Decrement Operators

Logical Operators

  • Concatenating Operators

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

The following are the list of arithmetic operators:

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

The following example uses the arithmetic operators:

Comparison operators allow you to compare two operands.

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

The following are the list of comparison operators in PHP:

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

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

PHP provides the following logical operators:

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

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

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

Incrementing/ Decrementing Operators

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

The following table illustrates the increment and decrement operators:

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

Concatenating Operator

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

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

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

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

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

PHP operators precedence

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

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

However, some operators have higher precedence than others.

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

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

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

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

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

PHP Operators

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

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

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

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

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

Arithmetic Operators: 

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

+

Addition

$x + $y

Sum the operands

Subtraction

$x – $y

Differences the operands

*

Multiplication

$x * $y

Product of the operands

/

Division

$x / $y

The quotient of the operands

**

Exponentiation

$x ** $y

$x raised to the power $y

%

Modulus

$x % $y

The remainder of the operands

Note : The exponentiation has been introduced in PHP 5.6. 

Example : This example explains the arithmetic operator in PHP.

Logical or Relational Operators:

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

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

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

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

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

Example : This example describes the comparison operator in PHP.

Conditional or Ternary Operators :

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

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

?:

Ternary

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

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

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

=

Assign

$x = $y

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

+=

Add then Assign

$x += $y

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

-=

Subtract then Assign

$x -= $y

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

*=

Multiply then Assign

$x *= $y

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

/=

Divide then Assign (quotient)

$x /= $y

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

%=

Divide then Assign (remainder)

$x %= $y

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

Example : This example describes the assignment operator in PHP.

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

+

Union

$x + $y

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

==

Equality

$x == $y

Returns true if both has same key-value pair

!=

Inequality

$x != $y

Returns True if both are unequal

===

Identity

$x === $y

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

!==

Non-Identity

$x !== $y

Returns True if both are not identical to each other

<>

Inequality

$x <> $y

Returns True if both are unequal

Example : This example describes the array operation in PHP.

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

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

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

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

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

Example : This example describes the string operator in PHP.

Spaceship Operators :

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

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

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

Please Login to comment...

Similar reads.

  • Web Technologies
  • PHP-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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
  • Language Reference

Logical Operators

Example Name Result
$a and $b And if both and are .
$a or $b Or if either or is .
$a xor $b Xor if either or is , but not both.
! $a Not if is not .
$a && $b And if both and are .
$a || $b Or if either or is .

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence .)

Example #1 Logical operators illustrated

The above example will output something similar to:

Improve This Page

User contributed notes 14 notes.

To Top

Texas Tech Now

Texas tech k-12 middle schooler shines on stage and in the classroom.

August 14, 2024

Texas Tech K-12 Middle Schooler Shines on Stage and in the Classroom

Daynne Baldwin, a sixth grader in Texas Tech’s online school, excels in reading as well as writing books and is a seasoned theater veteran.

When Daynne Baldwin was 2 years old, her mother Jennea (pronounced Dane and Jeh-NEE-ah, respectively) was already researching alternatives to traditional school. Jennea owns a music studio with business hours from 3-8 p.m. If her daughter was in school from roughly 8 a.m. to 3 p.m., the successful business owner knew she wouldn’t be seeing much of the youngster. That’s when Texas Tech K-12 hit Jennea’s radar. But it wasn’t to be until much later.

Daynne Baldwin

By the time Daynne was in kindergarten, Jennea had the opportunity to start her own private school, which ended up with about 20 students. That plan worked through Daynne’s second grade year, but that was 2019. When COVID hit the next spring, the school became unfeasible and too stressful for Jennea to continue. Jennea also knew typical homeschooling was not her best option as the thought of piecing things together herself without a set curriculum was something she didn’t feel confident about. 

“In the back of my mind, Texas Tech ’s K-12 program was always there, and I thought, ‘This is the perfect time to just give it a try and see what happens,’” Jennea recalled. “I’m very structured, and education has always been important to me. I didn’t want there to be any gaps in Daynne’s education.” 

There was another reason Texas Tech’s fully online K-12 program appealed to Jennea. She explained what she saw in her private music lesson students: kids would be 5 years old, full of questions and creative. But as they started school, year by year, she would see that spark diminish. She said the older her students got, the more tired they were. They weren’t inquisitive or particularly creative – they just wanted to be told what to do to get the score they needed to win a competition or to pass a theory test. 

That’s not what Jennea wanted for her daughter. She mused that the world changes so fast, with more and different technology and other challenges, it needed more creativity and problem-solvers, not fewer.  

“By the time they graduate, we’ve spent all those years taking that (creativity) out of them, and then it’s like, 'OK, now go back to what you had when you were 5 years old.”

Daynne Baldwin

Now, as Daynne is a flourishing sixth grader, Jennea says there are certainly no education gaps – as the newly minted 12-year-old is a voracious reader, an accomplished writer and has been in five musical productions in the past two years. She’s anticipating two more roles this fall.   

One concern – that dissolved rather quickly – was the socialization aspect, or lack thereof, of an online school. With the extra time Daynne has by finishing her lessons around noon each day (they only work on lessons Monday through Thursday), she has become more involved in theater, which, her mom says, is her social outlet. But also, the duo has visited Texas Tech’s new DFW site a couple of times for Texas Tech K-12 special events. That has allowed them to meet other Red Raider students and families.  

Evolving into Reading and Writing

Both mom and daughter were quick to give their own explanations of how a young elementary school student who didn’t really like reading has blossomed into an exceptionally talented, smart and knowledgeable middle schooler.  

“I just wanted her to read,” Jennea said. “One thing that was helpful for Daynne was, instead of me trying to work with lists of books, I would leave things out, like kids’ magazines and comic books and anything that had words on it but wasn’t technically a book.” 

“I really liked comic books when I was little and graphic novels,” Daynne interrupts.  

“She’ll say I’m a book nerd,” Jennea continues, darting a glance at her daughter. “I love reading. She wasn’t really interested in reading, and then when she was about 7, she picked up a book and said, ‘I think I want to read this.’”  

Jennea decided to get out of the way, stand back and watch. In no time, Daynne was reading a book every few days – sometimes 300 pages or more. 

Jennea and Daynne Baldwin

Jennea credits Texas Tech K-12’s focus on English language arts (ELA) for much of the change in Daynne.  

“I can see that it’s instilled such a love for writing and reading. She already kind of enjoyed those, but I love the focus on ELA in the program,” Jeannea said. “I think it’s helped nurture those skills in a way that she loves, not in a way that felt forced. I think, too, it’s the flexibility it gives us. She has more time to read. I’ve seen dramatic improvement in her reading.” 

“I read too much,” Daynne again interjects dryly, with a slight eyeroll and a grin.  

Jennea said Daynne has always been gifted in coming up with stories and ideas, and once she started figuring out how she could put those thoughts on paper, in writing, it just grew. Because Daynne finishes coursework in a few hours, with all that extra time, Jennea says she can explore all her interests and passions.  

Daynne and Jennea visit the Harry Potter Forbidden Forest Experience in Leesburg, Va.

“She told me she was going to start writing a novel,” Jennea said. “She’s been reading Harry Potter. She said she was going to take the Harry Potter characters and make them into her own story.” 

Daynne interjects again, making a face of disgust. “It was a TERRIBLE book! I should just burn that thing!” 

Taking the Stage 

Daynne attributes her love of theater to a summer camp that sparked her interest. She enjoyed it so much, she started doing full productions, her first one in 2023 at a theater in Irving, Texas, that unfortunately, has closed.  

Daynne poses at the red-carpet premiere of her short film “Final Signoff,” created by her at the Movie Institute in Frisco, Texas.

“Now I’m on my fifth one; I’m hoping to be in two more this fall,” she said, enthusiastically. “I was 10 when I did my first one last year.”  

At the time of this interview, Daynne was about to be in “Clue The Musical,” where there are several different endings. The cast has cards that an audience member comes up and pulls from to choose which ending will be played out. Daynne was working to learn them all. The young thespian also is what is known as the triple threat: actor, dancer, singer.  

Daynne’s venture into Ballet Folklorico

According to Mom, Daynne has done many types of dancing – ballet for a little bit, but it was too strict and structured – Daynne nods her head. She also has participated in Ballet Folklorico and Irish dancing, moving her attention to different countries. Now her focus is on musical theater.  

A Day in the Life 

As is typical for online students, each finds their own rhythm for getting coursework completed. Daynne usually does one subject per day, whichever one she feels like, but she doesn’t do schoolwork on Fridays. There might be a little bit of “homework” in the afternoons. 

“If there’s anything she needs help with, I’m available then,” Jennea says. 

“I usually don’t need any help,” Daynne cuts in, with a bit of snark and a side glance at her mom. 

Daynne’s field trips to the Fort Worth Museum of Science.

Jennea explains they take Fridays to go to a museum or some other creative outing.  

Also, they do six-week spurts, get as much finished as they can, and then they take off a week – a vacation week – or if they need time off if one of them is sick, or if something comes up with a show, that flexibility is built in. 

“Then we start over again with our six-week spurt,” Jennea said. “You can motivate yourself to dig a little deeper when you know there’s that light not too far down the road.” 

Educational Advantages 

Jennea is quick to point out Texas Tech K-12’s advantages over traditional school. The curriculum sparks many conversations for them, because she sees exactly what Daynne is working on, and they can use that to have conversations about whatever they want to talk about over breakfast or lunch. 

“If you want to make sure creativity and freedom of expression are nurtured, most definitely this program gives you that,” she said. “Sometimes there are topics she may not agree with. Or if we’re talking about history, it gives us the opportunity to have those discussions and look at it from many different perspectives – I like that, I feel like that’s what keeps her mind open.  

“I feel like it gives me the opportunity to play a more active role in her education, making sure everything is covered and she’s getting a good education,” Jennea added. 

php assignment expression

Jennea also points out the necessity for students in the school to learn time management and independence. She said Daynne laughs at her mom’s big spreadsheet, their goals for the week, but then her daughter just gets to it. Daynne opens the online school platform, Blackboard, and looks at what she needs. She starts working on it and plans out how that’s going to happen for the day.  

“I know that being able to do that is a skill a lot of my private students don’t have,” Jennea noted. “I also know it’s through no fault of their own. It’s just that everything has been scheduled and planned for them.” 

Jennea believes, in addition to creative problem-solving, being able to think in an organized way is going to benefit Daynne. She says being able to move back and forth from independent learning or working to being with others is the way of the world now. We’re not always in an office – there are times we have to work on our own. 

Highly Recommend 

Jennea highly recommends the program for families needing flexibility – that’s the main perk and being able to approach topics from different perspectives. Also, Daynne’s ability to function well in different situations shows the maturity she’s gained from independent study.  

“She helps me in the studio a lot in the afternoons – she’ll greet parents and visit with them in the waiting room,” Jennea relates, glancing admiringly at her daughter. “She’ll take younger kids who aren’t where they’re supposed to be and make sure they get where they need to be. There are times when parents will ask me, ‘How old is she?’ I’ll say 11, and they’ll say, ‘I can’t believe how she can speak on these different topics, and she’s well-spoken.’ That’s where the real testament comes, when other people can notice and comment on it.”  

Daynne with their two Great Pyrenees, Dandelion and Kayumi

For now, Daynne’s aspiration is to become either an actress or an English and theater teacher. Even with her studies, her shows, their four dogs and a rabbit, and only being in sixth grade, she has time to ponder the possibilities. But she also is quick to recommend Texas Tech K-12 and brag on her proficiency with the program. 

“It’s been a wonderful experience. I enjoy all the courses very much, and my teachers have been very helpful,” the young student exclaimed. “I am able to focus on my writing and theater, which is nice. The flexibility is most definitely the biggest advantage and being able to spend time with my mom. This school is definitely not for everyone, but it is for some people, and one of those people could be you.” 

You may also like

Alumna inspires next generation of scientists, engineers and mathematicians, graduating apparel designer says education doesn’t end here, texas tech alumna proves red raider spirit of overcoming.

PHP Tutorial

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

Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

In the example above, the variable $x will hold the value 5 , and the variable $y will hold the value "John" .

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Think of variables as containers for storing data.

A variable can have a short name (like $x and $y ) or a more descriptive name ( $age , $carname , $total_volume ).

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ( $age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!

Advertisement

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

The following example will produce the same output as the example above:

The following example will output the sum of two variables:

Note: You will learn more about the echo statement and how to output data to the screen in the PHP Echo/Print chapter .

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

You will learn more about strict and non-strict requirements, and data type declarations in the PHP Functions chapter.

Variable Types

PHP has no command for declaring a variable, and the data type depends on the value of the variable.

PHP supports the following data types:

  • Float (floating point numbers - also called double)

Get the Type

To get the data type of a variable, use the var_dump() function.

The var_dump() function returns the data type and the value:

See what var_dump() returns for other data types:

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

String variables can be declared either by using double or single quotes, but you should be aware of the differences. Learn more about the differences in the PHP Strings chapter .

Assign Multiple Values

You can assign the same value to multiple variables in one line:

All three variables get the value "Fruit":

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.

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

2 Answers 2

In the documentation you will find following note:

Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the > return value of foo() is put into $a.

So in your statement $b is assigned true before the comparsion with $a.

Alviaz's user avatar

Excellent question. The documentation is not wrong, but there's a special case here that has higher priority than operator precedence.

Within an if-statement, PHP parses assignments before comparisons, because it needs to know the result of the assignment to be able to compare it to the rest of the expression.

If your if-statement were parsed according to operator precedence, you'd end up with:

The left-hand side of the assignment must point to a memory address where PHP can store the result. Basically, left of the = must be a variable name. Since the rules of operator precedence would break that (more important) rule in your if-statement, PHP actually parses your if-statement as follows:

rickdenhaan's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged php expression variable-assignment or ask your own question .

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

Hot Network Questions

  • Why does Air Force Two lack a tail number?
  • Do non-necessarily symmetric, minimal IC-POVM exist in all dimensions?
  • What is Causing This Phenomenon? Is it the Geometry Package?
  • Claims of "badness" without a moral framework?
  • Package 'gettext' has no installation candidate, but package exists
  • Density of perfect numbers
  • A study on the speed of gravity
  • Why do instructions for various goods sold in EU nowadays lack pages in English?
  • Why did evolution fail to protect humans against sun?
  • Why would luck magic become obsolete in the modern era?
  • Characterization of normed spaces based on violation of parallelogram law
  • What is the lowest feasible depth for lightly-armed military submarines designed around the 1950s-60s?
  • "Undefined" when attempting analytical expression for a RegionIntersection and its Area in V14.0
  • Union of lists with original order
  • When would it be legal to ask back (parts of) the salary?
  • Is groff ignoring `.nh` command?
  • I submitted a paper and later realised one reference was missing, although I had written the authors in the body text. What could happen?
  • Can Genesis 1:26 be used to infer that God is a "genus"?
  • If there is no free will, doesn't that provide a framework for an ethical model?
  • Why are these simple equations so slow to `Solve`?
  • How do you determine maximum frequency of AD574A 12-bit ADC?
  • Sharing course material from a previous lecturer with a new lecturer
  • WW2 Bombers continuing on one of 2 or 4 engines, how would that work?
  • Shift right by half a trit

php assignment expression

IMAGES

  1. PHP Assignment Operators

    php assignment expression

  2. PPT

    php assignment expression

  3. PHP Tutorial For Beginners 16

    php assignment expression

  4. PHP Regular Expression Example

    php assignment expression

  5. PHP ASSIGNMENT OPERATORS

    php assignment expression

  6. 5: Expressions in PHP

    php assignment expression

COMMENTS

  1. PHP: Assignment

    In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression.

  2. PHP Assignment Operators

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

  3. PHP Assignment Operators

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

  4. PHP: Expressions

    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.

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

  6. PHP Assignment Operators: Performing Calculations

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

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

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

  9. php

    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.

  10. PHP assignment operators

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

  11. Expressions

    If assignment-expression designates an expression having value type, see assignment for scalar types If assignment-expression designates an expression having handle type, see assignment for object and resource types .

  12. Variable Assignment, Expressions, and Operators in PHP

    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:

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

  14. PHP Operators

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

  15. PHP: Basics

    For more information on this kind of assignment, see the chapter on Expressions . PHP also offers another way to assign values to variables: assign by reference.

  16. PHP Conditional Operator: Examples and Tips

    The PHP Conditional Assignment Operator is a shorthand method for assigning values based on ternary, Elvis, and Null Coalescing Operators.

  17. PHP: Logic

    PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.

  18. Texas Tech K-12 Middle Schooler Shines on Stage and in the Classroom

    Daynne completes a science experiment for a school assignment. Daynne with instructor Amy Boyd during Raiderpalooza in January at Texas Tech DFW Now, as Daynne is a flourishing sixth grader, Jennea says there are certainly no education gaps - as the newly minted 12-year-old is a voracious reader, an accomplished writer and has been in five ...

  19. while loop in php with assignment operator

    The expression in your example $info = mysql_fetch_object($data_jurisdiction) checks whether the $info, the assigned value from mysql_fetch_object() is equal to true, after type juggling.

  20. Houston Astros: Penn Murfee to begin rehab assignment

    Houston Astros reliever Penn Murfee to begin rehab assignment in recovery from Tommy John surgery. By Matt Kawahara, Staff writer Aug 14, 2024.

  21. PHP Variables

    Note: When you assign a text value to a variable, put quotes around the value. Note: Unlike other programming languages, PHP has no command for declaring a variable.

  22. php

    Within an if-statement, PHP parses assignments before comparisons, because it needs to know the result of the assignment to be able to compare it to the rest of the expression. If your if-statement were parsed according to operator precedence, you'd end up with: The left-hand side of the assignment must point to a memory address where PHP can ...