PHP the basics

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.

1. 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 above.

When you create a new PHP file must include your PHP code between these special tags.

2. Syntax

PHP’s syntax is very similar to other programming languages such as Perl or C. Block of codes are separated using curly brackets {}

<?php
if($is_enabled){
    echo 'Hello World!';
}
?>

As in most 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 (//), multi line 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 multi line comment 
print('Not executed');  
The print statement above is not executed  */

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:

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:

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, i hope think...

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 http://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, include_once, require_once.

8. Strings and REGEX

Because php is mainly aimed at processing data for human reading such as a blog, php has some very powerful text manipulation functions and for a better understanding i will only go over some basic uses. The example below shows the use of str_replace to fine and replace all copy's of a word.

$text = "Today foo went to bar town to buy a loaf of foo bar bread. When foo got to the bar store he fond there was no more foo bar bread."
$replace = str_replace("foo", "davis", $text);
echo $replace;

The above will change all instances of foo to davis. Another more powerful method is preg_replace and preg_match which uses the Regular expression language to filer though text. php regular expressions seems to be a quite complicated area especially if you are not an experienced Unix user. Historically regular expressions were originally designed to help working with strings under Unix systems. Using regular expressions you can easy find a pattern in a string and/or replace it if you want. This is a very powerful tool in your hand, but be careful as it is slower than the standard string manipulation functions.

The regular expressions basic syntax

To use regular expressions first you need to learn the syntax of the patterns. We can group the characters inside a pattern like this:

An example pattern to check valid emails looks like this:

^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$

The code to check the email using Perl compatible regular expression looks like this:

$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
$email   = "thetooth@ameoto.com";
if(preg_match($pattern,$email)){
    echo "Match";
}else{
    echo "Not match";
}

Now let's see a detailed pattern syntax reference:

Regular expression (pattern)

Match (subject)

Not match (subject)

Comment
worldHello worldHello JimMatch if the pattern is present anywhere in the subject
^worldworld classHello worldMatch if the pattern is present at the beginning of the subject
world$Hello worldworld classMatch if the pattern is present at the end of the subject
world/iThis WoRLdHello JimMakes a search in case insensitive mode
^world$worldHello worldThe string contains only the "world"
world*worl, world, worldddworThere is 0 or more "d" after "worl"
world+world, worldddworlThere is at least 1 "d" after "worl"
world?worl, world, worlywor, woryThere is 0 or 1 "d" after "worl"
world{1}worldworlyThere is 1 "d" after "worl"
world{1,}world, worldddworlyThere is 1 ore more "d" after "worl"
world{2,3}worldd, worldddworldThere are 2 or 3 "d" after "worl"
wo(rld)*wo, world, worldoldwaThere is 0 or more "rld" after "wo"
earth|worldearth, worldsunThe string contains the "earth" or the "world"
w.rldworld, wwrldwrldAny character in place of the dot.
^.{5}$world, earthsunA string with exactly 5 characters
[abc]abc, bbacccsunThere is an "a" or "b" or "c" in the string
[a-z]worldWORLDThere are any lowercase letter in the string
[a-zA-Z]world, WORLD, Worl12123There are any lower- or uppercase letter in the string
[^wW]earthw, WThe actual character can not be a "w" or "W"

9. Basic Web Site

I'd like to take you though a simple but effective page manager based on the one used in WhiteCrane. This script uses flat-files for storing pages.

The script is stored in the main index.php file and works off a simple $_REQUEST function to get the pages and send to the user. This makes it very light and easy to modify plus adding any other features will be possible.

example.txt (rename to index.php).

+