Like most programming languages, PHP lets you create variables in your scripts. A variable is a storage container that holds a value. This value can change as the script runs. You can:
- Assign any value you like to a variable
- Access the value stored in a variable, and
- Change a variable’s value at any time.
Variables are useful because they let you write flexible scripts. For example, a script that can only add 3 and 4 together isn’t very useful. A script that can add any two values together, though, is much more flexible.
Creating a variable
To create a new variable in PHP, you can just write the variable’s name:
$myVariable;
Notice the dollar (
$
) symbol before the variable name. All PHP variables have a dollar symbol in front.
This is known as declaring a variable. It’s also a good idea to give the variable an initial value at the time you declare it — this is known as initializing the variable:
$myVariable = 23;
Note: If you don’t initialize a new variable then it takes on a value of
null
.Changing a variable’s value
You’ve just seen how to assign a value to a variable: you simply write the variable name, followed by an equals sign, followed by the value you want to assign.
To change a variable’s value, simply assign the new value:
<?php $myVariable = 23; $myVariable = 45; $myVariable = "hello"; ?>
The first line of code creates a new variable with a numeric value of 23, while the second line changes the variable’s value to 45. The third line changes the value again — this time to a string of text, “hello”.
PHP is a loosely-typed language, which means you can change the type of data that a variable holds whenever you like. In the above example,
$myVariable
starts off holding a number, and finishes by holding a string of text.Using a variable’s value
To use the value of a variable in your script, simply write the variable’s name. For example, to display the value of
$myVariable
you’d use:<?php echo $myVariable; ?>
To add the values of two variables
$x
and $y
together and display the result, you could write:<?php echo $x + $y; ?>
0 comments:
Post a Comment