FFD - Visit the site
ICMS

12 January 06

Beginner PHP Tutorial 1: PHP Syntax & Integration with HTML

PHP Syntax

If you have ever coded in Perl or C before PHP should be quite familiar to you, as the makers of PHP took ideas from both languages to make it. When writing php code you must remember to place all your php code into the php tags. These are:

<?php and ?>

You can also cut off the ‘php’ on the opening tag but this is not compatible with all php setups due to an option which can be set to disable the short open tag (to prevent confusion with xml) so I recommend you always use the longer open tag. These tags help the php interpreter to find your code.

Another rule to remember is that each line of php code should be ended with a semicolon (;) except for certain times which I will cover later. Just remember this, else you will have lots of php errors popping up when you run your scripts.

Finally, every php file must have a .php file extension so hello.php, calc.php and functions.php are correct files whereas hello.txt, calc.xml and functions.doc are incorrect, except when your server is setup to handle these extensions as php scripts.

Integration with HTML

PHP Code can be slapped right into html pages (as long as they have a php extension) so having

<b><?php echo 'hi'; ?></b>

is absolutely valid. If statements can also be placed around html code, which I will show you in the Conditions and Operators tutorial.

PHP’s integration with html is extremely handy and means putting a html design and some php code together is very easy.

Some Useful Functions

In PHP you can place data onto the page by using

print('data');

or by using

echo 'data';

I almost always use echo since it is easier and quicker to type in. By using the echo or print function you send data to the browser. Note that because “echo” is a special php thing (I can’t remember what they call it) you don’t need the brackets you need on most functions so the previous example of echo is perfectly valid, but it only works on echo and some other special php ‘things’.

Calculations

To calculate an addition/subtraction/division etc. you can use a really simple:

echo 15 + 8;

...to place the sum of 15 and 8 (23) onto the page using the echo function we studied eariler.

For division you must use the forward slash (/) since this is more readily available on the keyboard than the actual division sign. Also, you must use the star for multiplication (*) for the same reason.

Comments

Jason at Jan 25, 03:25 AM #

Finally, a guide that tells you what signs are for, I’m a beginner and i used to search for php tuts / guides, but they didn’t explain a thing! Now I actually know what the is for THANKS ALOT, but can you make more of these guides please?

Scross at Jan 26, 05:19 AM #

Thanks again! As I said before, I am making some more very soon.

Comment

Next up: Beginner PHP Tutorial 2: Variables and Values