Reassigning variables
Learn to change a variable's value and increment or decrement it.
Changing a variable's value
When you assign a new value to a variable, the old value is gone and the new one takes its place. This is called reassignment.
Example: you write $city = "Berlin";, then later $city = "Hamburg";. Now $city holds Hamburg; Berlin is gone.
You can confirm it with echo: echo $city; prints Hamburg.
Reassignment is very common in programs; for example, when a user enters a new city, the old value is replaced.
Increase or decrease by one: ++ and --
To increase a variable by one, use ++: $count++;. This is the same as $count = $count + 1; but shorter.
To decrease by one, use --: $count--;.
Example: you set $visitors = 100;, then write $visitors++;. Now $visitors holds 101.
This short form is handy for counters and step counts; later you will also meet shortcuts like +=.
Exercise Reassign and increase the visitor count
Assign 100 to $visitors. Then reassign it to 150. Increase by one with $visitors++. Print the final value with echo; end with \n.
Show example solution
Reassign with $visitors = 150;, increase with $visitors++;, then echo $visitors; echo "\n";.
Example solution:
<?php
$visitors = 100;
$visitors = 150;
$visitors++;
echo $visitors;
echo "\n";
Test yourself
-
What does $count = 5; $count = 12; echo $count; print?
$count = 5; $count = 12; echo $count;- 5
- 17
- 5 12
- 12
Show answer
12 — Correct! Reassignment erases the old value; the last value, 12, is printed.
-
Add ++ to increase by one
$count____;Show answer
$count++; -
What does $count = 10; $count++; echo $count; print?
$count = 10; $count++; echo $count;- 11
- 10
- 101
- 1
Show answer
11 — Correct! ++ increases by one; 10 + 1 = 11 is printed.