PHP Variables (PHP Basics)
Now you have the basic layout down to an art, it is time to make our basic script more dynamic and we will be firstly doing this using variables, variables are strings that change
In the following example we will be assigning variables and using them within the exciting script
<html> <head>PHP Test Page</head> <body> <p>Jack is wearing green trousers</p> <?php // Define your variable $name = 'Jill'; // Now display the variable we have set echo "<p>$name is wearing a blue skirt</p>"; ?> </body> </html>
This may sound very simple and pointless at the moment but the further you get into PHP, the more you will realize just how much you use variables ... Please note that when you echo a variable you must enclose it within double quotes, single quotes will not work, you can echo variables on their own in the following way:
<?php // Define your variable $color = 'red'; // Display variable echo $color; ?> //You can also display a variable like this: <?php // Define your variable $color = 'red'; echo '<p>My favorite color is '; echo $color; echo ' what is yours?</p>'; //This will display: My favorite color is red what is yours? ?>
Now we know how to display single variables we can move onto displaying multiple variables.
<?php // Define variables $name = 'Jill'; $age = '23'; $email= 'jill@example.com'; // Build a sentence with all the variables echo "$name is currently $age years old, you can contact her on $email"; ?>
The sentence above is all well and good but it is a little bland, now lets make it a little dynamic
<?php // Define variables $name = 'Jill'; $age = '23'; $email= 'jill@example.com'; // Build a sentence with all the variables echo "$name is currently $age years old, you can contact her <a href=\"mailto:$email\">here</a>"; ?>
You will notice the slashes added to the left of the double quotes, these are important to keep the string from generating errors.
No related posts.

