PHP Assignment Operator

What do you mean assignment? I thought I was out of school.

The assignment operator (=) assigns the value, or expression, to the variable; and yes, it’s different from the equality comparison operator (==). This is one of the most commonly made mistakes for beginner programmers: using the assignment operator when a comparison operator is required.

The following syntax is required for the PHP assignment operator:

 

$variable = value (or expression)

 

The assignment takes the expression on the right and assigns it to the variable on the left.

 

<?php// Assign a value to a variable
$best_php_tutorial_youtuber = "Dino Cajic"; // of course// Assign an expression to a variable
$best_expression = 5 + 7;/** Another expression
 *  These two strings are concatenated
 *  and are then assigned to the 
 *  variable on the left.
 */
$another_expression = "Hello " . "there";?>

 

This is where it starts getting a little weird. You can assign a value to a variable and then assign that variable to another variable. You can keep going as many times as you want, but the code readability will suffer.

 

<?php$x = ($y = 2) + 22;?>

 

Let’s see how PHP would process the assignment operator example above:

  1. PHP starts by assigning the value 2 to the variable $y.
  2. A new expression is formed: $y + 22.
  3. That expression is evaluated. The value 2 is substituted for $y and is then added to 22:2 + 22 = 24.
  4. The new value, 24, is assigned to $x. Variable $x now contains the value 24.

We can now use both the $x and $y variables.

 

<?phpecho $x; // prints 24
echo $y; // prints 2?>

 

For readability purposes, I suggest that you’re as explicit as possible when assigning values to variables. The following code is a lot easier to read than what we did in the previous example.

 

<?php$y = 2;
$x = $y + 22;?>

 

PHP Tutorial Series

Continue your learning with these articles

PHP Constants

We’re starting to be consistent.

PHP – P14: Constants

Constants are similar to variables except that they cannot change. They can’t change since constants are stored in the read-only-data segment.

PHP Assignment Operator

What do you mean assignment? I thought I was out of school.

PHP – P15: Assignment Operator

The PHP assignment operator (=) assigns the value, or expression, to the variable; and yes, it’s different from the equality comparison operator (==).

PHP Arithmetic Operators

What’s Arithmetic?

PHP – P16: Arithmetic Operators

Arithmetic deals with the study of numbers, especially with operations on those numbers, such as addition, subtraction, multiplication, and division. In mathematics, those operations are called arithmetic operations. Arithmetic operators are then the operators that are used in arithmetic operations.

Leave a Reply