What's a variable
Imagine we have a task to output the phrase Father! two or even five times. We can approach it in a straightforward way:
<?php print_r('Father!'); print_r('Father!');
That’s the way to go in a simple case, but if the phrase Father! starts to appear again and again and in different parts of the program, we would have to duplicate it. And imagine we need to change the phrase, which happens quite often. That’s where problems begin. We would have to find all blocks of code where the phrase Father! was used and replace it. We could approach it differently though. Instead of duplicating our phrase, it’s sufficient to create a variable to store it.
<?php $greeting = 'Father!'; print_r($greeting); print_r("\n"); print_r($greeting);
Look at the line
$greeting = 'Father!'. We assign the value
'Father!' to the variable named
$greeting. In PHP variable names always start with a dollar sign $.
Once the variable is created, we can start using it. We replace with it all occurences of our phrase. While the code is being executed, the interpreter (the one that executes the php code) reaches the line
print_r($greeting), replaces the variable with its value and executes the code. As result, we’ll have the following output:
To name a variable you can use any set of valid characters which includes letters of the latin alphabet, numbers, hyphen
- and underscore
_. Note that a variable name can’t start with a number. Variable names are case sensitive, i.e.
heLLo are two different names and therefore two different variables.
The number of varibles is unlimited and big programs contain dozens and even hundreds of thousands variable names:
<?php $greeting1 = 'Father!'; print_r($greeting1); print_r($greeting1); $greeting2 = 'Mother!'; print_r($greeting2); print_r($greeting2);
There is a convention to create variables as close as possible to the code that uses them, in order to make it easier to analyze the program.
Create a variable named
$motto and assign to it
What Is Dead May Never Die!. Output the value of the variable.
Variable — a way to store information and give it a name to be reused in code later.
Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on Github.