Now that you know the PHP syntax, let's look at actually using it.
Before we go on, it's important to know that PHP can be used in any part of any page. Before any HTML is processed, after your </body> tag, and everything in between.
Let's make our first page; Hello World.
<html>
<body>
<?
# This will display your text
echo "Hello World!";
?>
</body>
</html>
Looks like:
Hello World!
Now to break this down:
-
Open HTML and BODY tags
-
Open syntax - allows us to use PHP
-
When you call on the "#", it creates a comment. Comments are not useful for coding, but they are great for leaving notes for yourself or others, and debugging.
-
"echo" is the command (referred to as a function), and will display the text between the quotes. Open quotation, text, close quotation, semicolin.
The semicolin means that's the end of that statement - finished and PHP will look for the next command to execute.
-
Close syntax
-
Close HTML and BODY tags
Comments:
There are 3 types of comments, but they all do the exact same thing.
-
# - an entire line for a comment
-
// - last part of the line comment
-
/* comment */ - block comment
Examples of these look like this:
<?
# this will cover the entire line
echo "Test"; // this is typically used after something important
/* and this will
cover everything
in this section */
?>
Semicolins:
After your line of code, or statement (Except for comments), always use a semicolin. NEVER forget them!
echo function:
the echo function is the same as print in many other languages. I recommend using echo because it's one character shorter. 20% faster to load, 20% less typing.
Anytime you want to display some sort of text, you use the echo function. Your text can be enclosed by double quotations or single. If it started with double, for example, it has to end with double.
example:
<?
echo "1. this will show up <br />"; // echo also accepts html
echo '2. this will show up <br />'; // single quotes work
echo "3. this will NOT work <br />'; /* starting with a double quote, ending with a single is erronous */
echo '4. this won't work either, can you figure out why?';
?>
The first two lines work flawlessly.
The last two will not work. Line #3 starts with a " but ends with a ' - which will cause a "Parse error:"
Parse error: syntax error, unexpected $end in /home/client/public_html/directory/echo.php on line 6
Exercise:
Figure out why echo #4 gives you a parse error.
Hint: look at the colors in the example
Your task:
Create a new php file called echo.php and get it to display some text. Upload it to your server, and message me the link. If you have questions or need help, feel free to message me or consult the internet guru of all, Google.