Chances are you’re familiar with the Hello World exercise by now. It’s the starting point for learning almost any programming language. PHP is no different. So let’s dive right into it. How do we display things using PHP?
<?php echo "Hello World!"; ?>
Which would display “Hello World!” on our users screen.
Now there are a few things to take note of. First off see how that echo statement ends with a semicolon. Every command in PHP must end with a semicolon. If you forget to use semicolon or use colon instead after a command you will get an error message like this
Parse error: parse error, unexpected ':', expecting ',' or ';' in echo.php on line 7
However in the above example above omitting the semicolon won’t cause an error because the echo statement was immediately followed by a closing PHP tag. This is generally the only situation when you will avoid the above mentioned Parse error – however as a general rule you shouldn’t rely on that and should simply put the closing semicolon.
Next you need to make sure you escape any quotations and apostrophe’s in you’re echo’d statement. For example if you wish to display to the user: Hello “Bob” it’s Monday – we would do the following:
<?php echo "Hello \"Bob\" it\\'s Monday"; ?>
We will take a closer look at escaping characters and variable expansion next.
Subsequently you can also echo out the values of a variable. Let’s say we have a variable – $myname – and we wish to display its value. We have two options for this:
<?php echo $myname; ?> <?=$myname?>
The latter method is a short syntax which allows you to quickly echo out stored variables. This will only work if your server is configured with short_open_tag – most modern day hosting companies are though. If you are unfamiliar with variables we take a closer look at them in our PHP Variables tutorial.