Difficulty: Moderately Easy
Things You’ll Need:
- PHP 5, installed and properly configured
- PHP IDE or a text editor
- Web server (preferably Apache)
- MySQL database server configured for work with PHP
Echo Variables Using PHP Very Simply
Step1
Pay attention to the general syntax of the echo function:
void echo ( string $arg1 [, string $...] )
If you are new to PHP (or programming in general), the above example might look incomprehensible and frightening, but it is actually very easy in practice.
Step2
Write a very simple example:
$name="John Smith";
echo $name;
This script defines a name variable, which stores the value--in this case, John Smith. If we want to print the value of the name variable on-screen, we do it with the echo function.
Try a More Difficult Example
Step1
Write a more difficult example--one that does not use a string but displays today's date. First, you get the date using the date() function, and then you output the result using the echo function.
$today = date("Y-m-d");
echo "Today is: $today.";
Step2
Apply special effects if you so desire. For instance, you can center the text, make it bold, print it in italics and so on. Plain HTML is used for this purpose.
Learn to Echo in an Advanced Way
Step1
Use the echo function to output several variables at once. Here is a more complex example that uses an environmental variable ( $browser=$HTTP_USER_AGENT ) in addition to the already familiar variables like $today, $time and $name:
<?
$today=date("d-m-Y");
$time=date("H:i:s");
$browser=$HTTP_USER_AGENT;
$name="John Smith";
echo ("Hello $name,");
echo ("It is $time and the date is $today. Your browser is $browser");
Step2
Expect the first line of this script to print "Hello John Smith,". The second line will print the current date and time and the type of browser of the visitor. The output will be on two lines--because you are using the <br> tag to mark the end of the line, not because you have written each of the echo commands on a new line. The value for the type of browser is obtained from the $browser=$HTTP_USER_AGENT environmental variable, which is one of the many environmental variables (i.e., variables that give information about the server, the user agent or the user IP) in PHP.
Step3
Concatenate variables (or merge them, in layman's terms) or pass multiple parameters consecutively instead of concatenating them. The choice is yours, and the end result is the same.