Current Location: Home> Latest Articles> PHP Basic Assignment Operator Guide: How to Efficiently Assign Values to Variables

PHP Basic Assignment Operator Guide: How to Efficiently Assign Values to Variables

M66 2025-07-30

What is the Basic Assignment Operator

In PHP, the basic assignment operator is used to assign a value to a variable. This operator is represented by the equals sign (=).

For example, the following code assigns the number 5 to the variable $x and the string "Hello World" to the variable $y:

<span class="fun">$x = 5;</span>
<span class="fun">$y = "Hello World";</span>

At this point, $x has a value of 5, and $y has a value of "Hello World".

Usage of the Basic Assignment Operator

Assigning Variables to the Result of an Expression

In PHP, variables can be assigned the result of an expression, not just constants.

For example, the following code assigns the sum of variables $a and $b to the variable $c:

<span class="fun">$a = 5;</span>
<span class="fun">$b = 10;</span>
<span class="fun">$c = $a + $b;</span>
<span class="fun">echo $c;  // Outputs 15</span>

At this point, $c has a value of 15.

Assigning Variables to Null

When using the basic assignment operator, a variable can also be assigned a null value, which means the variable has no value.

For example, the following code assigns null to the variable $x:

<span class="fun">$x = null;</span>

At this point, $x has a value of null, meaning it's empty.

Assigning Multiple Variables Simultaneously

PHP allows developers to assign values to multiple variables in a single line of code.

For example, the following code assigns the values 1, 2, and 3 to the variables $x, $y, and $z:

<span class="fun">$x = 1;</span>
<span class="fun">$y = 2;</span>
<span class="fun">$z = 3;</span>

Then, using the list() function, the variables are reassigned new values:

<span class="fun">list($x, $y, $z) = array($y, $z, $x);  // Now $x = 2, $y = 3, $z = 1</span>

At this point, $x has a value of 2, $y has a value of 3, and $z has a value of 1.

Using Operators for Chained Assignment

PHP also allows chaining assignment operations in a single line of code, making the code more concise.

For example, the following code assigns the value 1 to the variables $x, $y, and $z at once:

<span class="fun">$x = $y = $z = 1;</span>

At this point, all three variables have a value of 1.