The One Page Quick Start Guide to PHP

Welcome to the quickest Get Started with PHP guide you will ever read. There is no quicker guide to PHP. When I learned PHP I had to read pages of lesson guides just to get to what I really needed to know. I wanted to write code. I didn’t want to read a book. This guide is here to save you time.

This Teach Yourself PHP lesson is written on one short page. This is a beginners class. After following this lesson you will be able to write your own PHP code and scripts.

This guide is not for the anally retentive. You won’t learn all the ins-and-outs or whys-and-wherefores of PHP programming. This How to Program in-PHP guide is purpose designed to get you up and running with your own scripts as fast as possible. We will stick to basic essentials and ignore the crap that usually accompanies PHP tutorials.

PHP is easy. No need to learn exact definitions yet. You’re a beginner. Learn the basic ideas and ‘words’ and build on the basics later. There are right and wrong ways to code; learn them later.

This guide is great for reviewing basic PHP words. Bookmark the guide for when you need to refresh your PHP knowledge.

The quickest guide to PHP ever written

This section is an overview of basic PHP words and scripting concepts. Get familiar with the words in bold text. Skim read this section a couple of times then quickly make keyword notes (spider diagrams) of what you know about PHP.

There is a PHP Quiz to follow this guide. All answers are given with examples and explanations. The test section is where you will learn to use PHP.

The short examples shown in this guide section are here to help you get comfortable with PHP words and to help you recognise PHP phrases when you see them. Skim read the examples. They are not intended for deep study.

Before we begin, answer these 2 questions:

  1. What do you already know about PHP?
  2. What do you want to do with PHP?

Take 2 minutes to quietly answer those questions.

PHP Overview

The two most important PHP facts are:

  1. We show we are using PHP by writing <?php in front of our code. This starts the PHP engine.
  2. We show we are no longer using PHP by writing ?> after our code. This stops the PHP engine.

If your code does not begin with <?php and end with ?> then it won’t be recognised as PHP and it will do nothing you expect it to do.

PHP words

PHP is like English. We learn to speak basic English then we get creative and write stories. We learn PHP the same way. In this guide we will speak about PHP the same way we speak about the English language.

Comments are useful.

We add comments to code to make code easier to understand. Comments are not processed by the PHP engine. They are present for humans.

Comments on a single line can be tagged by two forward slashes like // . No closing tag required.

Comments on a single line can also be tagged by a forward slash and an asterisk. This requires a closing tag made of an asterisk and a forward slash. Like this /* Comment */

Comments that span multiple lines can be opened with a forward slash and an asterisk then closed with an asterisk and a forward slash.

// This is a comment

/* This is a comment */

/**
*  This is a comment
**/

/* None of these comments will be processed by PHP. */
// These comments are for humans to read

/*
This is a comment
*/

/**
This is a comment
**/

/****
* This is a comment
***/

Semicolons end phrases like this;

ECHO sends output to the screen.

PRINT sends output to the screen.

RETURN is like a secret passed around the code. We use ‘return’ to go back to wherever we came from, usually carrying new information with us. That information can then be used within a script or can be echoed or printed to screen.

We input, process and output data called strings. A letter, a number, a word, a group of words.. are all data strings. Any input string that is not a PHP code word must be encapsulated in quotation marks.

// Display 'Hello' on screen
// Use the echo code word and put (speech) quote marks around the 'Hello' string.
// Close the sentence (statement) with a semicolon.
echo 'Hello';

// Print 'Hello' on the screen
print 'Hello';

// This will not print 'Hello' to the screen
return 'Hello';

Variables are like English pronouns such as ‘it’, ‘this’ and ‘that’. Variables are names that represent strings.

Variables are used to hold static information. We make up a name for a variable, write the name with a dollar sign in front of it (dollars are $valuable) then equate the $variable to a string value.

// We give meaning to variables like this
$dollar = '1 dollar is worth 1 Euro';

We can change the value of a variable whenever we feel like it.

<?php

$word = 'Hello';
echo $word;

// The word is hello

// Change the value of $word
$word = 'Hi';
echo $word;

// The word is now 'Hi';

// Variables hold variable values

?>

Full stops (periods) join values together.

// Make 3 variables
$one = 'One';
$two = 'Two';
$three = 'Three';

// Output the variables in one line as a continuous sequence
echo $one.$two.$three;

// The output is
// OneTwoThree

We can use quotation marks in echo and print statements to add content before and after the string stored in a variable.

// Define variable values
$one = 'One';
$two = 'Two';
$three = 'Three';

// Show the values on screen with a space separating each value
echo $one.' '.$two.' '.$three;

// The output is now
// One Two Three

Compare the above example with this one.

// Define variable values
$one = 'One';
$two = 'Two';
$three = 'Three';
$space = ' '; // This is a space character

// Show the values on screen with a space separating each value
echo $one.$space.$two.$space.$three;

// The output is still
// One Two Three

Single Quotes around strings ensure the string is used exactly as written. If a variable is written within the string of an echo statement then that variable will show on screen as its name and not as the data it stores.

Double Quotes let us use variables in our statements and show the output of our variables.

// Give values to our variables
$one = One;
$two = Two;
$three = Three;

// Print something on the screen
echo "$one, $two, $three";

// The output is
// Once, Two, Three

echo '$one, $two, $three';
// The output is
// $one, $two, $three

Variables used within single quotes are printed exactly as they are written.

Variables used within double quotes return their stored value when printed.

We do not need to use quote marks when our input is stored in a variable.

/* The output of this echo statement.. */
echo $something;

/* ..is the same as this echo statement.. */
echo "$something";

/* ..and the same as this one too */
echo ''.$something.'';

/* Notice the full-stops in the last statement. We literally
*  join $something with nothing i.e. '' and $something and ''
*  There is no content to output from the single quotes
***/

Arrays are variables on steroids.

An array is like a written note with a numbered list on it. If you wrote a list of colors on a scrap of paper and gave the list a name, like The Color List, you would be doing the real world equivalent of writing an array called $the_color_list filled (populated) with a list of colors.

We can create an array list for the colors of the rainbow.

// Store the colors of the rainbow in an array
$the_color_list = array(red,orange,green,blue,indigo,violet);

As of PHP 5.4.x we can also create an array by writing just

// We can populate list items into an array like this too:
$the_color_list = [red,orange,green,blue,indigo,violet];

We can see the value of an item in an array (list) by referring to the name of the list (array) and the item number we want to view.

// Give me the value stored on line 0 of the list
echo $the_color_list[0];

// The result is "red"

An array list starts with line 0 unless we create a different mapping sequence.

// Let's create an array to hold the colors of the rainbow and the color's order in the list.
$the_color_list = ["red"=>"color 1","orange"=>"color 2","yellow"=>"color 3","green"=>"color 4","blue"=>"color 5","indigo"=>"color 6","violet"=>"color 7"];

/*
   In this array the index we use to retrieve a color's order number is the color's name e.g.
   The index is:
       red, orange, yellow, green, blue, indigo, violet
   The values that can be retrieved are:
       color 1,color 2, color 3, color 4, color 5, color 6, color 7
*/

The cleaner way to write the above is this:

$the_color_list = [
    "red"=>"color 1",
    "orange"=>"color 2",
    "yellow"=>"color 3",
    "green"=>"color 4",
    "blue"=>"color 5",
    "indigo"=>"color 6",
    "violet"=>"color 7"
];

We see the data stored in a specific row of the array by asking for it.

// Let us see what order the color red is within the rainbow.
// In other words, what is 'indexed' by 'red'?
print $the_color_list[red];

/* The output of our request to see what is stored in the 'red' row is.. */

// The array row reads "red" => "color 1"
// The value assigned to row 'red' is

color 1

We can print the full array content with print_r($array).

// Show me the data in the array
print_r($the_color_list);

The screen output for the first version and second version of the array will look like this:

// Data from the original array

Array (
  [0] => red
  [1] => orange
  [2] => green
  [3] => blue
  [4] => indigo
  [5] => violet
)

// Data from the mapped array

Array (
  [red] => color 1
  [orange] => color 2
  [yellow] => color 3
  [green] => color 4
  [blue] => color 5
  [indigo] => color 6
  [violet] => color 7
)

We can see the array content and information about the array data with var_dump($array).

var_dump($the_color_list);

The data output of the array dump of both arrays will print

// Dump of the original array

array(6) {
  [0]=> string(3) "red"
  [1]=> string(6) "orange"
  [2]=> string(5) "green"
  [3]=> string(4) "blue"
  [4]=> string(6) "indigo"
  [5]=> string(6) "violet"
}

// Dump of the mapped array
// This shows: number of rows in the list (7), type of data in column 2 (string) and the count of characters in column 2 of each row (7).

array(7) {
  ["red"]=> string(7) "color 1"
  ["orange"]=> string(7) "color 2"
  ["yellow"]=> string(7) "color 3"
  ["green"]=> string(7) "color 4"
  ["blue"]=> string(7) "color 5"
  ["indigo"]=> string(7) "color 6"
  ["violet"]=> string(7) "color 7"
}

The data in an array can be manipulated. We can add extra rows, append rows, prepend rows, shuffle rows randomly, reorder rows logically, delete rows and more.

Let’s put echo, print, return, variables and arrays together to do something with them.

<?php

$question = 'Do you like these fruits?';
$fruit = array('apple', 'orange', 'banana', 'cherry');

echo $question.'<br />';
echo $fruit[0].' or '.$fruit[2]; // Notice the full-stop .

echo 'Or<br />'; // Notice the inclusion of HTML

print "$question<br />"; // Print does the same as echo here
print $fruit[1].' or '.$fruit[3];

return // Return serves no real purpose here

?>

Now for the more active PHP words

Variables and arrays are the nouns of PHP. We store information in them. What we put into them is what we get out of them. Echo, print and return are like PHP verbs: they perform actions; but they lack character. Allow me to introduce you to PHP functions.

Before we meet functions, you need to know about braces.

Braces tie code statements together into a group called a ‘code block’. They look like { and }.

We use braces when we write IF statements and user defined FUNCTIONS.

We do not add a semicolon after a closing brace.

FUNCTION is the word we use when we want to name a block of code.

Functions are like memes and ideas that can be reused within our code. We use the code by saying its name.

Functions look like this:

function SeeMe() {
   print "Hide Me";
}

Functions are used like this:

SeeMe();

Here is how that function is written and used in a script:

<?php

function SeeMe() {
   print "Hide Me";
}

SeeMe();

?>

// The output of SeeMe() is

Hide Me

Function names are case sensitive. SeeMe() is different to SeEmE().

We can call functions at any point in our code execution. We could keep all functions to the top of our scripts and call them into use toward the bottom of our scripts.

Functions can be called within functions.

Do not write a function within a function. Write functions separately of each other and call them into use wherever they are needed.

Functions can return data as their output and that data can then be used elsewhere within a script.

function hello() {
    $greeting = 'Hello You!';
    return $greeting;
}

// This says "Hello You!"
echo hello();

// This says "Hello You! How are you, buddy?"
$buddy = ' How are you, buddy?';
echo hello().$buddy;

// Notice the value of $greeting is only sent to screen when the function is echoed or printed etc...

Functions are Dynamic.

Functions are like production factories. They work to build a product. The product is delivered to wherever it is called into use. The output of a function is often dynamic and depends on the raw materials handed to the function.

A function that takes in raw materials (called arguments) looks like this

// Create a function called 'make' that accepts the two input arguments $fruit and $product.
// $fruit and $product are just variables. They take any value we give them.
// The values of $fruit and $product can be used within our function

function make( $fruit, $product ) {
    // Use our variables (arguments)
    echo "We are making $fruit $product today";
}

To make apple source we would call the function with arguments.

// Call our make() function and assign values to our arguments.
// make ( $fruit, $product ) becomes...

make( Apple, Source );

The product delivered to the screen (echoed) would read

// This is the output of make(Apple, Source)

We are making Apple Source today

IF statements let us say what we would like to happen when different events occur. IF statements are usually mixed with ‘operators’ like and, or, less than, greater than and equal to.

AND & OR are logical operators. They let us tie conditions together. They work the same way they do in spoken English.

  • OR is usually written as a double pipe like this ||
  • AND is usually written as a double ampersand like this &&

Less Than, Greater Than and Equal To are called comparison operators.

  • Less Than is written as <
  • Greater Than is written as >
  • Equal To is written as ==

IF statements look like this:

// This if statement will output 'The test is correct' if the value of $test is the same as the value of $correct
if ( $test == $correct ) {
    echo "The test is correct";
}

An IF statement that uses logical operators looks like this:

// If the value stored by $apple is the same as $fruit
// AND
// The value of $potato is the same as $vegetable
// Then 'Apple is a fruit and potato is a vegetable' is printed on screen

if ( $apple == $fruit && $potato == $vegetable ) {
    echo "Apple is a fruit and potato is a vegetable";
}

We can say “not” in PHP.

We use an exclamation mark to say ‘Not!’ Think of this as shouting ‘Wow! No way! Stop!’.

Not Equal To is written as !=

// Set some variables
$test = 'One';
$correct = 'Two';

if ( $test != $correct ) {
    echo "The test is incorrect";
}

// $test and $correct are not the same so nothing is echoed to the screen.

// Create some variable values
$exchange = 'Same';

if ($exchange == 'Same') {
    $dollar = '1 dollar is worth 1 Euro';
} elseif ($exchange == 'Up') {
    $dollar = '1 dollar is worth more than 1 Euro';
}

echo $dollar;
// The output is '1 dollar is worth 1 Euro'

// Give exchange a different value

$exchange = 'Up';

if ($exchange == 'Same') {
    $dollar = '1 dollar is worth 1 Euro';
} elseif ($exchange == 'Up') {
    $dollar = '1 dollar is worth more than 1 Euro';
}

echo $dollar;
// The output is '1 dollar is worth more than 1 Euro'

PHP ‘verb words’ that perform actions are properly called functions. The functions we write for ourselves are called user defined functions.

When we write PHP code we are actually scripting.

Native PHP functions are pre-written scripts. When we combine functions to do useful and amazing things with web servers we are combining pre-written scripts, hence we are ‘scripting’.

Output Buffering is like recording the output of PHP code ready for replaying it later.

Output Buffering is how we capture the output of PHP code before the output is used. We can save the output in a variable for later use. We can even save the output to a file and use it as a file cache of the code output. Output buffering is pretty neat.

We start capturing output with ob_start().

We stop capturing output and return the out with ob_get_clean().

// Let's record some output (and keep it to ourselves)
ob_start();
  // Do something
  echo "Output buffering is a modern day miracle";
// Let's reveal the output for others to see and delete the evidence (clear the output cache)
ob_get_clean();

Or we can

  • store the output in a variable with ob_get_contents().
  • stop capturing output with ob_end_clean();
  • then use the output somewhere else within our code (the output is stored as a string in a variable).
// Begin capturing output from this point in our code onwards
ob_start();
   // Output something
   echo "The date is ".date();
   // Capture (store) the captured code output into a variable
   $content = ob_get_contents();
// We've captured enough data so stop recording
ob_end_clean();

// Do something with the captured content
return $content;

Let’s summarize the basics before we step up a gear and answer a few questions.

Putting it all together

PHP scripts are written with verbs called functions and pronouns called variables. A variable can store a single string of data or a variable can be given genius status among variables and be made to store a list of data strings in rows and columns called an array.

Variables can be strung together to join their data output in sequence. A string of variables looks like a chain linked by dots and is as easy to make as saying $one.$two.$three.

Functions can be called to action almost anywhere within a script. They deliver their output wherever they are called. When we call a function it reports back to its code block before it replies to us with its output. Some functions enjoy a right good ol’ argument. We can pass arguments to functions so our arguments can be considered within the code of the function before a reply is posted to us.

PHP has prepositions called operators.

We can compare strings of data stored within variables and we can compare the output of functions. We use the comparison operators when comparing data strings with each other. These are the less than sign, greater than sign and equality sign. They look like a fish when drawn together >=<>. We can even compare the data in a variable with the output of a function.

We can set conditions for when we want code to be read. We do this with an IF conditional statement.

We say and and or with && and ||. These are the logical operators. They like to operate if there are conditions such as “If you eat an apple && I eat an apple then there will be no more apples left to share”.

The Quiz

We had an editing error. This guide was published before ready for public view. Instead of hiding the guide we decided to keep it public. We will add the quiz over the next few days. We will error check and revise the guide too.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of

Free to your inbox

Join our mailing list to receive the latest news and updates from JournalXtra.

You have Successfully Subscribed!