Home » PHP Tutorial » PHP Assignment Operators

PHP Assignment Operators

Summary : in this tutorial, you will learn about the most commonly used PHP assignment operators.

Introduction to the PHP assignment operator

PHP uses the = to represent the assignment operator. The following shows the syntax of the assignment operator:

On the left side of the assignment operator ( = ) is a variable to which you want to assign a value. And on the right side of the assignment operator ( = ) is a value or an expression.

When evaluating the assignment operator ( = ), PHP evaluates the expression on the right side first and assigns the result to the variable on the left side. For example:

In this example, we assigned 10 to $x, 20 to $y, and the sum of $x and $y to $total.

The assignment expression returns a value assigned, which is the result of the expression in this case:

It means that you can use multiple assignment operators in a single statement like this:

In this case, PHP evaluates the right-most expression first:

The variable $y is 20 .

The assignment expression $y = 20 returns 20 so PHP assigns 20 to $x . After the assignments, both $x and $y equal 20.

Arithmetic assignment operators

Sometimes, you want to increase a variable by a specific value. For example:

How it works.

  • First, $counter is set to 1 .
  • Then, increase the $counter by 1 and assign the result to the $counter .

After the assignments, the value of $counter is 2 .

PHP provides the arithmetic assignment operator += that can do the same but with a shorter code. For example:

The expression $counter += 1 is equivalent to the expression $counter = $counter + 1 .

Besides the += operator, PHP provides other arithmetic assignment operators. The following table illustrates all the arithmetic assignment operators:

Concatenation assignment operator

PHP uses the concatenation operator (.) to concatenate two strings. For example:

By using the concatenation assignment operator you can concatenate two strings and assigns the result string to a variable. For example:

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

PHP Variables

In this tutorial you will learn how store information in a variable in PHP.

What is Variable in PHP

Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script. Here're some important things to know about variables:

  • In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
  • After declaring a variable it can be reused throughout the code.
  • The assignment operator ( = ) used to assign value to a variable.

In PHP variable can be declared as: $var_name = value;

In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number. Later we've displayed the variables values in the browser using the echo statement. The PHP echo statement is often used to output data to the browser. We will learn more about this in upcoming chapter.

Naming Conventions for PHP Variables

These are the following rules for naming a PHP variable:

  • All variables in PHP start with a $ 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 in PHP can only contain alpha-numeric characters and    underscores ( A-z , 0-9 , and _ ).
  • A variable name cannot contain spaces.

Note: Variable names in PHP are case sensitive, it means $x and $X are two different variables. So be careful while defining variable names.

Bootstrap UI Design Templates

Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.

Interactive Tools

BMC

php variable assignment with or

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

  • Best Practices ,

php variable assignment with or

How does PHP handle assignment expressions with multiple variables or complex expressions?

Hi everyone, I hope you're all doing well. I have a question regarding PHP assignment expressions, specifically when it comes to handling multiple variables or complex expressions. I have been studying PHP recently and came across some code examples where multiple variables are assigned at once or complex expressions are used in assignments. Can someone please explain to me how PHP handles this? I want to have a better understanding of how these expressions are evaluated and what happens behind the scenes. Any explanations or examples would be greatly appreciated. I'm looking forward to your responses. Thank you in advance! Best regards, [Your Name]

All Replies

princess98

Hi there, I've been working with PHP for quite some time now, and I can certainly provide some insights into how PHP handles assignment expressions with multiple variables or complex expressions. When it comes to handling multiple variables, PHP allows you to assign values to multiple variables in a single line using the assignment operator "=" followed by the values, separated by commas. This can make your code more concise and readable. For instance: php $x = 10; $y = 20; PHP goes through the expressions in order and assigns the corresponding values to each variable. So, in this case, $x will be assigned the value 10, and $y will be assigned the value 20. Now, let's dive into complex expressions. PHP is quite flexible when it comes to handling complex expressions in assignment statements. You can perform mathematical calculations, manipulate strings, utilize logical operators, or even incorporate functions within the assignment. Here's an example to illustrate this: php $result = ($x + $y) * 2 - pow($z, 2); In this case, the expression on the right-hand side is evaluated first. The sum of $x and $y is multiplied by 2, then the value of $z is raised to the power of 2, and finally, these two values are subtracted from each other. The resulting value is then assigned to the variable $result. As you can see, PHP allows you to build complex expressions using a combination of operators, functions, and variables, giving you great flexibility in your assignments. I hope this clarifies how PHP handles assignment expressions with multiple variables or complex expressions. Feel free to ask if you have any further questions or need additional examples! Best regards, User 2

Hey there, In my experience with PHP, assignment expressions with multiple variables or complex expressions are handled quite smoothly. PHP allows you to assign multiple variables in a single expression using the assignment operator "=". For example, let's say we have two variables `$x` and `$y`, and we want to assign them values 10 and 20 respectively. We can do it in a single line as follows: php $x = 10; $y = 20; Similarly, PHP also supports complex expressions in assignments. You can perform arithmetic operations, concatenate strings, or even use conditional statements within an assignment expression. Let me give you an example: php $a = 5 + 3; // assigns 8 to $a $b = "Hello, " . "World!"; // concatenates the strings and assigns to $b $c = ($x > 0) ? "Positive" : "Negative"; // assigns "Positive" or "Negative" based on the condition In these cases, PHP evaluates the expressions on the right-hand side of the assignment operator and assigns the resulting value to the variable on the left-hand side. I hope this helps to clarify how PHP handles assignment expressions with multiple variables or complex expressions. If you have any further questions, feel free to ask! Best regards, User 1

More Topics Related to PHP

  • What are the recommended PHP versions for different operating systems?
  • Can I install PHP without root/administrator access?
  • How can I verify the integrity of the PHP installation files?
  • Are there any specific considerations when installing PHP on a shared hosting environment?
  • Is it possible to install PHP alongside other programming languages like Python or Ruby?

More Topics Related to Examples

  • Can I leverage macOS-specific tools like Launchd or Automator to manage PHP processes or schedule tasks?
  • Can I mix HTML and PHP code in the same file? If yes, how?
  • How do I declare a boolean variable in PHP?
  • How do I declare an array variable in PHP?

More Topics Related to Explanations

  • How can I install PHP on Ubuntu using the apt package manager?
  • How can I scale PHP applications in the cloud to handle high traffic or load balancing?
  • Notice: Undefined variable: mine in C:\wamp\www\social\profile-view.php on line 58
  • how to pass a variable thru URL in php

Popular Tags

  • Best Practices
  • Web Development
  • Documentation
  • Implementation

php variable assignment with or

New to LearnPHP.org Community?

  • 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 Introduction
  • How to install PHP in windows 10 ?
  • How to Install PHP on Linux?
  • PHP | Basic Syntax
  • How to write comments in PHP ?

PHP | Variables

  • PHP echo and print
  • PHP | Data Types
  • PHP | Strings
  • Associative Arrays in PHP
  • Multidimensional arrays in PHP
  • Sorting Arrays in PHP 5

PHP Constants

  • PHP | Constants
  • PHP Constant Class
  • PHP Defining Constants
  • PHP | Magic Constants
  • PHP Operators
  • PHP | Bitwise Operators
  • PHP | Ternary Operator

PHP Control Statements

  • PHP | Decision Making
  • PHP switch Statement
  • PHP break (Single and Nested Loops)
  • PHP continue Statement
  • PHP | Loops
  • PHP while Loop
  • PHP do-while Loop
  • PHP for Loop
  • PHP | foreach Loop

PHP Functions

  • PHP | Functions
  • PHP Arrow Functions
  • Anonymous recursive function in PHP

PHP Advanced

  • PHP | Superglobals
  • HTTP GET and POST Methods in PHP
  • PHP | Regular Expressions
  • PHP Form Processing
  • PHP Date and Time
  • Describe PHP Include and Require
  • PHP | Basics of File Handling
  • PHP | Uploading File
  • PHP Cookies
  • PHP | Sessions
  • Implementing callback in PHP
  • PHP | Classes
  • PHP | Constructors and Destructors
  • PHP | Access Specifiers
  • Multiple Inheritance in PHP
  • Abstract Classes in PHP
  • PHP | Interface
  • Static Function in PHP
  • PHP | Namespace

MySQL Database

  • PHP | MySQL Database Introduction
  • PHP | MySQL ( Creating Database )
  • PHP Database connection
  • Connect PHP to MySQL
  • PHP | MySQL ( Creating Table )
  • PHP | Inserting into MySQL database
  • PHP | MySQL Select Query
  • PHP | MySQL Delete Query
  • PHP | MySQL WHERE Clause
  • PHP | MySQL UPDATE Query
  • PHP | MySQL LIMIT Clause

Complete References

  • PHP Array Functions
  • PHP String Functions Complete Reference
  • PHP Math Functions Complete Reference
  • PHP Filesystem Functions Complete Reference
  • PHP intl Functions Complete Reference
  • PHP IntlChar Functions Complete Reference
  • PHP Image Processing and GD Functions Complete Reference
  • PHP Imagick Functions Complete Reference
  • PHP ImagickDraw Functions Complete Reference
  • PHP Gmagick Functions Complete Reference
  • PHP GMP Functions Complete Reference
  • PHP Ds\Set Functions Complete Reference
  • PHP Ds\Map Functions Complete Reference
  • PHP Ds\Stack Functions Complete Reference
  • PHP Ds\Queue Functions Complete Reference
  • PHP Ds\PriorityQueue Functions Complete Reference
  • PHP Ds\Deque Functions Complete Reference
  • PHP Ds\Sequence Functions Complete Reference
  • PHP SPL Data structures Complete Reference
  • PHP Ds\Vector Functions Complete Reference
  • PHP DOM Functions Complete Reference
  • PHP Exercises, Practice Questions and Solutions

Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables.  There are a few rules, that need to be followed and facts that need to be kept in mind while dealing with variables in PHP:  

  • Any variables declared in PHP must begin with a dollar sign ( $ ), followed by the variable name.
  • A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x)
  • A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number.
  • A constant is used as a variable for a simple value that cannot be changed. It is also case-sensitive.
  • Assignment of variables is done with the assignment operator, “equal to (=)”. The variable names are on the left of equal and the expression or values are to the right of the assignment operator ‘=’.
  • One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers.
  • PHP is a loosely typed language, and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values. The same happens while conversion. No variables are declared before they are used. It automatically converts types from one type to another whenever required.
  • PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.

Data types used by PHP to declare or construct variables:

Example:   

Variable Scopes

Scope of a variable is defined as its extent in a program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed.  Depending on the scopes, PHP has three variable scopes:   

  • Local variables : The variables declared within a function are called local variables to that function and have their scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements.   

Output: 

  • Global variables : The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.

Output:   

Static variable : It is the characteristic of PHP to delete the variable, once it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use the static keywords and the variables are then called static variables.  PHP associates a data type depending on the value for the variable.  

You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static, and its memory is freed after the execution of the first function call.   

Variable Variables:-

  • PHP allows us to use dynamic variable names, called variable variables.
  • Variable variables are simply variables whose names are dynamically created by another variable’s value.

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

PHP Tutorial

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

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

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

PHP Arithmetic Operators

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

PHP Assignment Operators

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

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

Advertisement

PHP Comparison Operators

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

PHP Increment / Decrement Operators

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

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

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

PHP String Operators

PHP has two operators that are specially designed for strings.

PHP Array Operators

The PHP array operators are used to compare arrays.

PHP Conditional Assignment Operators

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

PHP Exercises

Test yourself with exercises.

Multiply 10 with 5 , and output the result.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

  • Language Reference

Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

Variable functions won't work with language constructs such as echo , print , unset() , isset() , empty() , include , require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Example #1 Variable function example

Example #2 Variable method example

Example #3 Variable method example with static properties

Example #4 Complex callables

  • is_callable()
  • call_user_func()
  • function_exists()
  • variable variables

Improve This Page

User contributed notes 6 notes.

To Top

COMMENTS

  1. Can I use logical OR || in PHP variable declaractions?

    5. For JavaScript, foo = bar || baz; is a commonly used expression, as the || operator has a coalescing behavior. PHP does not have this behavior with regard to the || operator, which returns a boolean value. As such, the more verbose code you originally posted: is your most readable, and preferable option.

  2. PHP: Assignment

    Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. ... An exception to the usual assignment by value behaviour within PHP occurs with object s, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

  3. 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. It is created the moment you first assign a value to it. ... Rules for PHP variables: A variable starts with the $ sign, followed by the name of the variable;

  4. PHP: Basics

    PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

  5. PHP: Variable variables

    Variable variables are a powerful feature of PHP that allows you to use the value of a variable as the name of another variable. Learn how to use them, what are the benefits and pitfalls, and how they differ from normal variables. This manual page also provides examples and links to related topics.

  6. Learn PHP: Learn PHP Variables Cheatsheet

    In PHP, the reference assignment operator (=&) is used to create a new variable as an alias to an existing spot in memory. In other words, the reference assignment operator (=&) creates two variable names which point to the same value. So, changes to one variable will affect the other, without having to copy the existing data.

  7. A Basic Guide to PHP Variables By Examples

    Summary: in this tutorial, you will learn how to use PHP variables to store data in programs.. Define a variable. A variable stores a value of any type, e.g., a string, a number, an array, or an object. A variable has a name and is associated with a value. To define a variable, you use the following syntax:

  8. PHP OR Operator

    The logical OR operator accepts two operands and returns true if either operand is true; otherwise, it returns false. In other words, the logical OR operator returns false if both operands are false. To represent the logical OR operator, PHP uses either the or keyword or the || as follows: expression1 or expression2. Or.

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

  10. PHP Variables: The Ultimate Guide

    Variables give developers the possibility of temporarily storing data to be used in PHP scripts (in PHP's case, this happens in the server's memory). This guide is all about working with variables in PHP. By the way, if you are just starting out with PHP, I recommend reading this guide first: Learning PHP: Get Started Using PHP.

  11. How to Define a Variable in PHP

    Here're some important things to know about variables: In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value. After declaring a variable it can be reused throughout the code. The assignment operator (=) used to assign value to a ...

  12. How does PHP handle assignment expressions with multiple variables or

    I've been working with PHP for quite some time now, and I can certainly provide some insights into how PHP handles assignment expressions with multiple variables or complex expressions. When it comes to handling multiple variables, PHP allows you to assign values to multiple variables in a single line using the assignment operator "=" followed ...

  13. PHP

    Assignment of variables is done with the assignment operator, "equal to (=)". The variable names are on the left of equal and the expression or values are to the right of the assignment operator '='. ... To do this we use the static keywords and the variables are then called static variables. PHP associates a data type depending on the ...

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

  15. PHP: Variable scope

    Variable scope in PHP determines the visibility and accessibility of variables in different contexts. This webpage explains the rules and concepts of variable scope, such as global, local, static, and superglobal variables, and how they are affected by functions, classes, and include statements.

  16. Variable Reassignment

    PHP Strings and Variables. Variable Reassignment. The word variable comes from the latin variāre which means "to make changeable." This is an apt name because the value assigned to a variable can change. ... During variable assignment or reassignment, the variable on the left of the assignment operator is treated as a variable (named ...

  17. PHP: Variable functions

    PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. ... //Assignment using ternary operator.}} abstract class MBR_ATTR {//A class full of attributes that objects ...

  18. PHP

    php variable assignment inside if conditional. 9. Assign variable within condition if true. 0. Assigning a variable a value depending on its value. 0. Assign value to variable using multiple conditional statement. 1. One PHP statement to use result of IF statement for assignment. 6.

  19. How does variable assignment in an expression work?

    FALSE: the boolean FALSE itself the integer 0 (zero) the float 0.0 (zero) the empty string, and the string "0" an array with zero elements an object with zero member variables (PHP 4 only) the special type NULL (including unset variables) SimpleXML objects created from empty tags TRUE: everything not listed above