PHP – The Basics – Tags, echo and if/else

One of the most basic things when writing code in PHP is to use the PHP tags which signify the beginning and the ending of the PHP code. You must have the tags in order for PHP to process the code you write. The tags are:

beginning tag:

<?php

ending tag:

?>

e.g

<?php
//code here
?>
 

You can have anything proceeding/preceding the PHP tags, but anything in between them must be valid PHP.

I advise you to only use the tags that I have stated above. Try not to use tags like:

<?
//some code
?>

or

<?= "Hello!" ?>
 

Shorthand tags are not 100% compatible on 100% of servers, however:

<?php
//some code
?>

is! 😉

We’ll start with something pretty simple and it is the echo statement.
This is an example of the echo statement:

<?php
echo "Hello you!";
?>
 

When the script is run, the page will display “Hello you!”.
Notice the semicolon? The semicolon (;) is a line terminator. It tells PHP that you are finished with that particular set of instructions, and that PHP can continue with the script until it reaches the end. If the semicolon is not present at the end of instructions/commands/statements/variables a error may be triggered as a result.

Now lets move on to something a little more useful, the if/else statement.

This is an example of an if/else statement:

<?php
if (5 > 10)
 {
 echo "5 is greater than 10";
 }
else
 {
 echo "5 is not greater than 10";
 }
?>
 

Okay with an if statement you must define the conditions of the if between the brackets. The aim of an if statement, is to get true returned (a boolean). If the condition returns false, then it will run the code in the else statement (if there is one).

In the code above the if statement will return false and display “5 is not greater than 10″ – understand?

Yeah its pretty easy at this level.
If I used this code:

<?php
if (5 < 10)
 {
 echo "5 is less than 10";
 }
else
 {
 echo "5 is NOT less than 10";
 }
?>
 

The if statement would return true, and therefore we would get “5 is less than 10″ printed out on the page.

When writing an if statement there are two important parts.

  1. The condition – this is contained in between brackets (5 < 10)
  2. The curly braces – { } – the code you want to execute should be placed in between the two curly braces. The only exception to this is when you only have one line of instructions like this:
<?php
if (5 < 10)
echo "5 is less than 10";
?>
 

That concludes this part of my help guide I hope it was useful to those starting to learn PHP.
If you want to look into the if/else statement more, look into elseif. The PHP manual is a great resource, so make good use of it. It contains everything you need to know about PHP (literally).

Feel free to comment on this post, I appreciate all the comments I receive! 😀

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Leave a Reply