I’ve been a PHP developer for more than 6 years now and time has come to start sharing some of my knowledge. It was my good friend, Martin Nordal, who introduced me to the language, and I’ve been hooked ever since. PHP is free, easy to learn, fast, secure and a great tool for anyone who ever needs dynamic content published on the world wide web. This post will give you a quick and brief introduction to PHP, how it works and how to code.
This tutorial requires:
- Basic HTML skills
- A plain text (text-only, no formatting) editor; notepad (standard in Windows), notepad2, notepad++ ..etc
- Access to a web server, running PHP (PHP 5.x is recommended)
What is PHP?
PHP (PHP Hypertext Preprocessor) is a scripting language, originally designed to produce dynamic web pages. Firstly, it is important to separate PHP as software and a scripting language. The scripting is what you’ll learn, while the software runs on the server and makes the magic happen. Most modern web servers come with PHP installed, it is free software everyone easily can get hold of. When developing, the main difference between HTML and PHP files is that you’ll save your files as .php instead of .html. Except for that, they’re both flat files with slightly different content. This is quite important as most web servers aren’t configured to parse regular .html files as PHP.
How does it work?
Imagine you loading this web page into your browser, what happens? The browser sends a request to the web server, asking to retrieve the web site’s main HTML and required files. The usual behaviour with plain HTML files, is that the server replies, returning all the static HTML data. With PHP, it’s slightly different. Before sending the files from the server, the PHP interpretor recognises the the request for a file with the .php extension. Then it parses the PHP blocks which (usually) modifies the HTML (dynamic), then returns the modified HTML. Therefore, unlike HTML and JavaScript, the source code is never open for everyone to see! PHP script modifies the HTML dynamically, and returns the result to the browser as plain regular HTML.
Do not be afraid if you don’t get this right away, you’ll understand it in soon.
Hello world!
It is time to write your first block of PHP, open your text editor and write the following code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My first PHP</title>
</head>
<body>
<p><?php echo('Hello world!'); ?></p>
</body>
</html>
Save the file as helloworld.php, upload it to your web server, open it in your browser. You should see a white page displaying nothing but “Hello world!”. If you look at the code above, it is all plain HTML, except for the one line within the body tags; That’s PHP! Look at the source code of the site in the browser (press Ctrl+U), notice that the PHP is gone and it’s all plain HTML.
The Basics
Delimiters
<?php /* PHP code here */ ?>
In order for the PHP interpretor (compilator) to separate the PHP (do process) from the HTML (do not process), we need to declare what’s PHP and what’s not. This is done by wrapping the PHP code blocks within the PHP delimiters (<!?php ... ?>).
General syntax
PHP is somewhat similar to all the other intermediate- and high-level programming languages. It’s easy to migrate and learn PHP if you already have some programming or scripting experience. The main difference is how variables are used in PHP.
- All lines (including function calls) ends with semicolons, example: echo();
- Variables are declared without data types.
- Variables are case sensitive
- Variables are declared and used with the dollar sign, example: $myVariable= 12;
- Variables can change data type at any time, without any casts, example: $var = 12; $var = ‘Hello'; $var = true;
- All variables can be compared with eachother, no matter the data type, example: if (123 == ‘123’) echo(‘Wait, what!?’);
- Data types are automatically casted when comparing different datatypes
- Use three comparison operators (===) to compare both value and datatype
- You can have as many blocks of PHP as you like in one document.
Examples:
<?php
$string = '123';
$integer = 123;
$float = 12.34;
if ($string == $integer)
{
echo('<p>$string\'s value equals $integer</p>'); // This will occur
}
if ($string === $integer)
{
echo('<p>$string is same value and datatype as $integer</p>'); // This will never occur
}
if ($string != $integer)
{
echo('<p>$string has not the same value as $integer</p>'); // This will never occur
}
if ($string !== $integer)
{
echo("<p>$string is not equal to $integer</p>"); // This will occur
}
?>
Output:
<p>$string's value equals $integer</p>
<p>123 is not equal to 123</p>
Operators
PHP supports all common operators.
- if, else, elseif (note; no space), switch
- ==, ===, ||, or (same as ||), &&, !, >, <
- for, foreach, while, do { .. } while()
Double quotes VS single quotes
PHP supports both single and double quotes when working with strings. There is however a difference. Everything in double quotes gets processed by PHP, which means that it slower than single quotes. Never use double quotes unless you have to! The following example should demonstrate the differences:
<?php
$var = 'PHP';
echo('<p>The variable is $var\n</p>');
echo("<p>The variable is $var</p>\n");
echo('<p>'.$var.' is the language</p>'."\n"); // The most efficient way
?>
Output:
<p>The variable is $var\n</p>
<p>The variable is PHP</p>
<p>PHP is the language</p>
Arrays
An array is a list or collection of data/variables defined as a variable. It’s one of PHP’s and other programming languages most powerful features, as it allows iterations and dynamic data. It is more or less a variable with a list of keys. You can use the keys to store, retrieve or remove data. PHP’s arrays are more or less a combination of a traditional Array, List and a Dictionary. You do not have to define it’s size, it expands automatically, keys kan be defined as both numbers and Strings.
Examples
<?php
/** Various ways to define arrays */
// Define empty array
$myArray = array();
// Define array with some values
$yourArray = array(1, 23, 45, 'cow', true, 65.3);
// Define an array as a "Dictionary" with keys and values
$dictionaryArray = array(
'key' => 'value',
'number' => 123,
5 => 'five',
'author' => 'Stig',
0 => 45
);
// Another way to define an Array (shorter)
$weekDays = [
0 => 'Monday',
1 => 'Tuesday',
2 => 'Wednesday',
3 => 'Thursday',
4 => 'Friday',
5 => 'Saturday',
6 => 'Sunday'
];
// Multi dimensional array
$books = [
[
'title' => 'The Hobbit',
'author' => 'J.R.R. Tolkien',
'prices' => array(
'US' => 19.99,
'EU' => 22.99,
'NOK' => 199.99
)
],
[
'title' => 'Agile Web Development with Rails',
'author' => ['Sam Ruby', 'Dave Thomas', 'David Heinemeier Hansson'],
'prices' => array(
'US' => 22.09,
'EU' => 24.09,
'NOK' => 239.45
)
]
];
/** Working with arrays */
// Adding data to the end of an Array
array_push($myArray, 'new data');
array_push($myArray, 1234);
$myArray[] = 4321;
$myArray[] = 'data new';
// Adding data by key. 1th key is always 0.
$myArray[4] = 'moar data'; // 5th entry (key + 1)
$yourArray[6] = 'arrays'; // 7th entry
// Adding data to the multidimensional array
$books[] = array(
'title' => 'Java Software Structures',
'author' => ['Lewis', 'Chase'],
'prices' => array(
'US' => 54.99,
'EU' => 56.99,
'NOK' => 199123.9901
)
);
// Accessing and modifying data
// Fetching values
echo('<p>First element in $myArray: '.$myArray[0].'</p>');
echo('<p>Accessing the "number" key in $dictionaryArray: '.$dictionaryArray['number'].'</p>');
// Modifying a value
$weekDays[5] = 'Caturday';
// Looping through arrays
// Get number of elements in myArray. Store in variable for performance.
$size = count($myArray);
for ($i = 0; $i < $size; ++$i) // do this $size times
{
// Print the value of the current element
echo($myArray[$i].'<br>');
}
// Demonstrates a simple foreach, loops through all elements
foreach ($yourArray as $value)
{
// Print the value of the current element
echo($value.'<br>');
}
// Demonstrates another foreach with access to keys
foreach ($weekDays as $key => $day)
{
// Print the data of the current element
echo($day.' is the '.($key + 1).'. day of the week<br>');
}
// Combination with multidimentional array
$size = count($books);
for ($i = 0; $i < $size; ++$i)
{
// Check if the current book has multiple authors (is array)
if (is_array($books[$i]))
{
// Multiple authors, print 'em all!
foreach ($books[$i]['author'] as $author)
{
// Print name and book title
echo($author.' ['.$books[$i]['title'].']<br />');
}
}
else
{
// One author, print his name and book title
echo($books[$i]['author'].' ['.$books[$i]['title'].']<br />');
}
}
?>
Output:
<p>First element in $myArray: new data</p>
<p>Accessing the "number" key in $dictionaryArray: 123</p>
new data<br />
1234<br />
4321<br />
data new<br />
moar data<br />
<br />
1<br />
23<br />
45<br />
cow<br />
<br />
65.3<br />
arrays<br />
Monday is the 1. day of the week<br />
Tuesday is the 2. day of the week<br />
Wednesday is the 3. day of the week<br />
Thursday is the 4. day of the week<br />
Friday is the 5. day of the week<br />
Caturday is the 6. day of the week<br />
Sunday is the 7. day of the week<br />
J.R.R. Tolkien [The Hobbit]<br />
Sam Ruby [Agile Web Development with Rails]<br />
Dave Thomas [Agile Web Development with Rails]<br />
David Heinemeier Hansson [Agile Web Development with Rails]<br />
Lewis [Java Software Structures]<br />
Chase [Java Software Structures]<br />
Functions
PHP has loads of functions and libraries, which all are documented and explained on http://php.net/. It’s a quick and great resource when developing PHP, as it’s basicly http://php.net/
Custom functions
This is just an introduction, so I won’t explain all the details, but the following example should explain the essentials:
<?php
// Make a list of invalid sentences to print
$invalidSetences = [
'Don\'t print me!',
'PHP sucks!'
];
// Function to print a paragraph on the page
function printParagraph($data)
{
// This makes the variable outside of the function accessible from within the function
global $invalidSentences;
// Make sure the input data is a string, is longer than 0 and isn't in the banned list
if (!is_string($data) || (strlen($data) == 0) || in_array($data, $invalidSentences))
{
return false;
}
else
{
// The sentence is OK, print it!
echo('<p>'.$data.'</p>'."\n");
}
}
printParagraph('Hello World!');
printParagraph('Yay, my first custom made function. Totally homebrewed!');
if (!printParagraph('PHP sucks!'))
{
printParagraph('PHP Rules!');
}
?>
Output:
<p>Hello World!</p>
<p>Yay, my first custom made function. Totally homebrewed!</p>
<p>PHP Rules!</p>
Object Oriented Programming (OOP) – Classes in PHP
OOP in PHP is a quite big subject and will be covered in a later post. I suggest you use the API for now: http://php.net/manual/en/language.oop5.php