All we've done so far is outputted some text using "echo." To stop you dying from boredom, we'll have a play with some variables. A variable is simply a box that holds a value or values. It is how PHP stores data and passes them between functions.
Without variables PHP and dynamic websites would be rendered useless! Dynamic web content that changes as a result of an input relies on data being stored and transferred around or between pages. Variables are the responsible for storing and moving data in this manner.
For you to properly understand variables, I think you should play with them some. But first, let's look at the main things that we can do to variables:
- Set a variable - assign them a value.
- Access a variable - read the value and use it.
- Re-set a set variable - re-assign them a value.
In PHP variables are defined by a $. Here, a variable is set, accessed, re-set and used again. A variable's value can be changed at any time.
$phrase = "Hello!";
echo "$phrase How are you?";
echo "$phrase It was nice seeing you again.";
I began by making a variable called "phrase." As variables begin with a $, the variable should look like this: $phrase.
This is what happens when the above code is executed:
- Indicates the start of a PHP code block.
The variable $phrase is made. It is then set with the string "Hello!"
- Outputs a static string and accesses the $phrase variable and outputs that also.
- Inserts a HTML paragraph tag to make some white space.
The variable $phrase is re-set and given the new value "Goodbye!".
Outputs a static string and accesses the new $phrase variable and outputs that also.
- Indicated the end of the PHP code block.
Wow! You just witnessed your first PHP variable in action! All we did was set and access the variable a few times, however, we can do so much more! The magic of PHP lets you set a variable in one place. For example, a user could complete a form and the user inputs could be held in a variable for use later.
- Use quotations for strings (not needed for numbers)