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 assignment operator:
$variable = value (or expression)
The assignment takes the expression on the right and assigns it to the variable on the left.
// 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.
$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.
5. We can now use both the $x and $y variables.
echo $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.
$y = 2;
$x = $y + 22;
Read the full article on my website
https://www.dinocajic.com/php-assignm...
Code for this tutorial
https://github.com/dinocajic/php-7-yo...
Full Code
https://github.com/dinocajic/php-7-yo...
PHP Playlist
• PHP Tutorial
--
Dino Cajic
Author and Head of IT
Homepage: https://www.dinocajic.com
GitHub: https://github.com/dinocajic
Medium: / dinocajic
Instagram: / think.dino
LinkedIn: / dinocajic
Twitter: / dino_cajic
My Books
An Illustrative Introduction to Algorithms
https://www.amazon.com/dp/1686863268
Laravel Excel: Using Laravel to Import Data
https://amzn.to/4925ylw
Code Along With Me - PHP: From Basic to Advanced PHP Techniques
https://amzn.to/3M6tlGN