
This tutorial will cover the basic syntax and common features of PHP. It assumes that you already know what is a server-side scripting language and you have already installed and set up PHP on your development machine.
If you want to learn PHP, you should start by reading this article, which covers the absolute basics of PHP programming language.
Table of Contents
- Syntax
- PHP Tags
- Variables
- Variable Types
- Control Structures
- Functions
- Include External Libraries
- Further Reading
1. Syntax
PHP’s syntax is very similar to other programming languages such as Perl or C. Block of codes are separated using curly brackets {}
if ($is_enabled) { echo 'Hello World!'; }
As in most traditional programming languages, in PHP too a semi-colon (;) marks the end of a statement, although the last statement before the PHP closing tag doesn’t require a semi-colon, because the closing tag automatically implies this. It is a good practice to use a semi-colon every time to improve code manageability and avoid ambiguity.
//this is a statement with semi-colon on the end. echo 'Hello World!';
Comments in PHP are of two types. Single-line comments and multi-line comments. Single-line comments starts with a double forward slash (//), multiline comments start with a forward slash followed by a star (/*) and marking the end of the comment with a star followed by a forward slash (*/). anything between the comments will be skipped by the PHP interpreter, this includes PHP comments, HTML statements, etc.
//this is a single-line comment echo 'Hello'; //this is a single-line comment also /* This is a multiline comment print('Not executed'); The print statement above is not executed */
2. PHP Tags
Every PHP script code is between an opening and an ending tag.
<?php //PHP code here ?>
There are four different types of opening-ending pairs. Although you can use all the four, it is strongly recommended to use the first presented from the code box below. (<?php ?>)
<?php //it is recommended to use this type //PHP code here ?> <? //also called short opening-closing tag, could be disabled from PHP configuration //PHP code here ?> <% //ASP style opening-closing tag, could be disabled from PHP configuration //PHP code here %> <script language="php"> //HTML style opening-closing tag //PHP code here </script>
When you create a new PHP file must include your PHP code between these special tags.
The PHP script doesn’t have to be in a separate file, the code could be embedded in HTML files too, if your Apache is set to parse PHP code in HTML files.
<div id="something"> <?php echo 'Embedded in HTML!'; ?> </div>
3. Variables
PHP variables always start with a dollar sign ($) sign. The variable name is case-sensitive meaning that $test and $TeSt are two separate variables.
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
$variable = 'this is a variable'; $another = 445; $Variable = 'third variable';
Predefined variables in PHP are the following:
- $SERVER
- $GET
- $POST
- $COOKIE
- $ENV
- $REQUEST
- $SESSION
- $FILES
- $HTTORAWPOSTDATA
- $GLOBALS
- $phperrormsg
- $httpresponseheader
- $argc
- $argv
You cannot set variables if it’s name is the same with one of the names from the above list.
Variable scope is the context (code block) in which it is defined. For example if a variable is defined outside of a function, it’s not visible inside of the function, in this case you must use the global keyword prefix.
$outside = 'me'; function test() { //without this statement the $outside variable is not available in this function global $outside; echo $outside; }
4. Variable Types
PHP has the following types:
- 4 scalar types: boolean, integer, float, string
- 2 compound types: array, object
- 2 special types: resource, NULL
We don’t have to set the type of a variable, PHP figure out the variable type depending on the context in which it is used. Also to define a variable of String type you must use either single quotes (”) or double quotes (“”) to define a value for it.
//this variable will be an integer $a = 12; //this will be a floating point number (float or double) $b = 44.35; //this will be a boolean $c = true; //this will be a string $d = 'text'; //this will be an array $e = array('first','second','third'); //this will be an associative array $f = array('one' => 1, 'two' => 2); //this will be an object, if the Something class exists and included $g = new Something();
You can perform basic mathematic operations on two or more variables. For example adding, subtracting, multiplying, etc.
$a = 1; $b = 2; echo $b + $c; //outputs 3
You can also concatenate variables with the help of the . (point) sign.
$a = 'Hello '; $b = 'World!'; echo $a .$b; //outputs Hello World!
5. Control Structures
There are different control structures in PHP, for example: if, else, for
The if statement performs a boolean operation on the passed expression. If it evaluates TRUE the code within the if statements block will be executed, if FALSE and if an else block is supplied, it will execute that code.
$a = 1; $b = 1; if ($a == $b) { echo 'if block'; } else { echo 'else block'; }
Try to assign different values to $a and $b to see the code execution flow.
The comparison between two variables are performed using a special equality operator, the == sign. Other important operators are: < lower than, > greater then, <= lower than equals, etc. You can read more about language operators at www.php.net/manual/en/language.operators.php
6. Functions
Functions are logical code blocks that helps keep your source code manageable. A function can have many different arguments and it must be defined before it is referenced in your PHP script.
//a function without any argument function Example() { //PHP code here } //a function with 2 arguments function Example2( $argument1, $other) { //PHP code here }
For easier understanding, you can think of arguments as variables. You pass along variables to functions to work with or simply pass along static values
function Test ($prefix, $another_value) { echo $prefix .$another_value; } $a = 445; $b = ' street'; Test($a,$b); //but you can also do this Test('Hello ', 'World!');
You can write any code inside a function that you would normally write outside of it.
7. Include External Libraries
For better source manageability you can segment your script into logical blocks, for example to create a basic calculator, you could basic arithmetic calculations in a PHP script file and presentation, user interface into another file, then you create a third file and include the two external files.
math.php
function add ($x, $y) { return $x+$y; } function subtract($x, $y) { return $x-$y; }
ui.php
function write_to_screen($result) { echo $result; }
calculator.php
include "math.php"; include "ui.php"; $a = 12; $b = 14; $add_result = add($a,$b); $subtract_result = subtract($a,$b); write_to_screen('Add: ' .$add_result); write_to_screen('Subtract: ' .$subtract_result);
The actual PHP script file inclusion is achieved by writing include and the path to the file you want to include. There are other methods to include files, e.g. require, includeonce, requireonce.
Further Reading
- PHP 5 Cheat Sheet
- Beginner’s Guide to PHP – Codepedia
- Jemjabella’s PHP Primer
- PHP 101
- PHP for Beginners by a Beginner
Comment goes here Is also a valid comment in php :linux:.
What do you mean?
"#" also denotes the start of an inline comment (i.e. "# Comment goes here").
Thanks for pulling this together. It's great to see the basics all in one place. Since I'm still learning myself, I use a lot of cheat sheets. I always have my iPhone with me, so I keep them there for handy reference - even offline.
The best PHP cheat sheet I've found so far is from these guys: http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=302760278&mt=8
They also have great cheat sheets for CSS and Javascript. Hope this is helpful.
Exelent posts
Thank you for posting!