The first step – part two


Last time in part one ( we setup a web server and looked at PHP output. This time in part two we will look at:

  1. variables
  2. functions
  3. scope and globals

If you’ve not read part one, then please do so before this part so that it will make sense.


Firefox® is a registered trademark of the Mozilla Foundation –

Ubuntu® is a registered trademark of Canonical Ltd –

“Raspberry Pi” is a trademark of the Raspberry Pi Foundation –

Apache and Apache HTTP Server are trademarks of The Apache Software Foundation –

Other names / logos can be trademarks of their respective owners. Please review their website for details.

I am independent from the organisations listed above and am in no way writing for or endorsed by them.

All example ‘code’ presented is written by myself, please feel free to copy for educational purposes only.

A reminder if it does not work

If something goes wrong, then you need to look in the error log file. On the Pi, this will be located in the ‘/var/log/apache2’ folder as ‘error.log’ and you can use the command ‘tail’ to see the most recent events as the file is appended to. In other systems, hunt around for ‘error.log’.


Think of a variable as a dynamically sized box. It is a container to hold what you want to store in it. Over time its contents can change, become bigger or smaller. An example would be ‘age’ of a person. For a given individual this will be set and then increase over time. Or it could be the list of participants who have signed up for a course where over time, some can be added and some drop out.

Variables have a type depending on what you want to store. This is so that the computer knows how to manage the variable on the available hardware. Thus translate the ‘data’ you store in a variable in to ‘bits’ (

Some variable types (such as an ‘array’ ( are containers for lots of other variables. PHP’s types are listed here:

PHP is a loosely typed language (, this means that the type of a variable is not known until a value is assigned to it. It can also change type as the program runs, Other languages have ‘strong typing’ which means that the type of the variable must be defined before it is used.

As we did in the last part, in the folder ‘mycode’, use ‘nano’ to create the file ‘vars.php’:

<!doctype html>

$one = "1";
$two = "a";
echo '<p>$one is of type:'.gettype($one).", containing $one.</p>";
echo '<p>$two is of type:'.gettype($two).", containing $two.</p>";
echo '<p>';
for($count = 0; $count < 10; $count++) {
    echo $count.":".$one.'-'.$two;
    if ($count < 8) {
        echo ", ";
    } else if ($count == 8) {
        echo " and ";
    } else {
        echo ".";
echo '</p>';
echo '<p>$one is of type:'.gettype($one).", containing $one.</p>";
echo '<p>$two is of type:'.gettype($two).", containing $two.</p>";

Note: PHP can use both ‘’ and “” as string containers. When the former, any variable syntax is not evaluated to show the variable value and with the latter it is. So if $one is 42, then ‘$one’ will show $one and “$one” will show 42.

Use a URL like ‘’ in a web browser to see the result:

So we can see how PHP is:

  • Able to tell the type of a variable from its first assignment.
  • Increment it sensibly, so with the ‘a’ character it becomes a ‘b’ and ‘1’ becomes ‘2’.
  • Change the type of a variable depending on its contents. So ‘$two’ has changed from a string to an integer.

We can also see one form of how loops are orchestrated with ‘for’ here – And this in general terms is perhaps the hardest thing about learning how to program, understanding one thing often depends on another and that another. This can be a ‘circle’ of dependency whereby you have to loop around gradually understanding each item before the whole makes sense. You do have to persevere and not give up!


In solving a problem where a computer is a part of the solution in terms of software, that problem will be broken down into many solutions that form the whole solution. Often a solution can depend on many other solutions and those solutions used more than once. It is like working in a multi-floor building performing many different tasks, you’ll use the stairs more than once. Software allows you to break down the solution into many smaller solutions, one form is a ‘function’ (we will cover classes and methods next time).

A ‘function’ can be used many times to do the same thing and can have ‘parameters’ as an input and thus produce a different result. Just like asking somebody for the time of day, same function different result depending on what time it is. Or asking about the time table for a bus, same function, but a different result if its bus number ‘42’ or ‘64’.

In our example we will create a function that lets you know when your meeting will be from now. It takes two parameters, the hour and minute of the meeting and then combines that with asking the computer for the current time. If you want to find out how your computer keeps its time updated then read about the ‘Network Time Protocol’ (, the ‘internet’ is more than just web pages!

In the folder ‘mycode’, use ‘nano’ to create the file ‘func.php’:

<!doctype html>

function meetingAt($hour, $min, $now) {
    $meeting = mktime($hour, $min, 0, $now['mon'], $now['mday'], $now['year']);
    $diff = $meeting - $now[0];
    echo '<p>Meeting at: '.$hour.':'.$min.' is in '.gmdate('G\h i\m \a\n\d s\s', $diff).'.</p>';

$meetings = array();
$meetings[] = array('h' => 10, 'm' => 30);
$meetings[] = array('h' => 12, 'm' => 45);
$meetings[] = array('h' => 15, 'm' => 10);

$now = getdate();
echo '<h1>Current time is: '.gmdate('G\h i\m \a\n\d s\s', $now[0]).'.</h1>';
foreach ($meetings as $meeting) {
    meetingAt($meeting['h'], $meeting['m'], $now);


Use a URL like ‘’ in a web browser to see the result:

We can see how:

  • The function is defined with the ‘function’ keyword with its name afterwards. This does need to be unique within the current scope (more on ‘Scope’ later).
  • There are parameters of ‘$hour’, ‘$min’ and ‘$now’ that are in the same syntax as we learned about in ‘Variables’.
  • Further down there is a call to another function ‘getdate()’ with no parameters to get the current date and time, which we store in ‘$now’. This we pass to our function ‘meetingAt’ as a parameter, it contains an array containing the different elements, like the current day, and critically array index ‘0’ contains a number which is the number of seconds since the 1st January 1970 – Unix or ‘epoch’ timestamp ( It is built into PHP ( so we don’t need to create it ourselves.
  • Then the ‘mktime’ PHP function ( is used to create a date/time for our meeting on the current day. Where we know the hour and minute of the meeting, but not the rest. It returns the epoch timestamp for the meeting time.
  • Because we now have two epoch times that are just number of seconds, then we can perform a calculation to work out the difference between the two and then output that.
  • Then we define our meeting times and because arrays have ‘indexes’ that can be strings, I’ve defined ‘h’ and ‘m’ to represent the hour and minute of the meeting. As each meeting has two values for the hour and minute, this is stored as an array. Thus we can have an array storing many arrays.
  • Then we have our actual output where we ‘loop’ over the ‘$meetings’ array with the ‘foreach’ keyword ( This allows us to iterate over each item in our array that happens to be an array with the hour and minute to pass to our ‘meetingAt’ function. And so because there are three items, then ‘meetingAt’ will be called three times.

Scope and Globals

The word ‘scope’ is perhaps is one of the most critical concepts to understand about software. It defines at any point what your ‘code’ can ‘see’. By ‘see’ this means ‘has access to’ and ‘access’ can be to ‘functions’, ‘variables’, ‘classes’ and ‘methods’. By ‘access’ this can be interpreted as ‘able to use’ but it does not mean ‘modify’ as you might be able to access a variable but not actually change it.

In PHP and other languages, scope is ring-fenced by the curly brackets ‘{}’. They are the dividers between one scope and another. A scope can contain one or more scopes, just like a ‘Matryoshka doll’ ( In PHP anything outside the uppermost brackets (top level scope) is in the ‘global scope’ and to access something like a variable in the global scope from within another scope then you need to use the ‘global’ keyword.

In the folder ‘mycode’, use ‘nano’ to create the file ‘scope.php’:

<!doctype html>
        <title>Scope and Globals</title>

echo "<h1>Scope and Globals</h1>";
echo '<table>';
$globalscopevar = 'global';
echo '<tr><td>Global</td><td>- 1</td><td>:</td><td>'.$globalscopevar.'</td></tr>';

function scope() {
    $functionvar = 'function';

    echo '<tr><td>Function</td><td>- 1</td><td>:</td><td>'.$functionvar.'</td></tr>';
    echo '<tr><td>Global</td><td>- 2</td><td>:</td><td>'.$globalscopevar.'</td></tr>';
    global $globalscopevar;
    echo '<tr><td>Global</td><td>- 3</td><td>:</td><td>'.$globalscopevar.'</td></tr>';

    for ($count = 1; $count < 3; $count++) {
        $loopvar = 'loop-'.$count;
        $functionvar = 'function-'.$count;
        $globalscopevar = 'global-'.$count;
        echo '<tr><td>Loop</td><td>- 1.'.$count.'</td><td>:</td><td>'.$loopvar.'</td></tr>';
        echo '<tr><td>Function</td><td>- 2.'.$count.'</td><td>:</td><td>'.$functionvar.'</td></tr>';
        echo '<tr><td>Global</td><td>- 4.'.$count.'</td><td>:</td><td>'.$globalscopevar.'</td></tr>';
    echo '<tr><td>Loop</td><td>- 2</td><td>:</td><td>'.$loopvar.'</td></tr>';


echo '<tr><td>Loop</td><td>- 3</td><td>:</td><td>'.$loopvar.'</td></tr>';
echo '<tr><td>Function</td><td>- 3</td><td>:</td><td>'.$functionvar.'</td></tr>';
echo '<tr><td>Global</td><td>- 5</td><td>:</td><td>'.$globalscopevar.'</td></tr>';
echo '</table>';



Use a URL like ‘’ in a web browser to see the result:

We can see that:

  • We’ve used a HTML ‘table’ to format the output.
  • The number after the hyphen represents the index of access to test that variable.
  • After the colon, the value of the variable at that time or blank if it cannot be accessed – it is not in scope. Look in the ‘error.log’ for ‘Undefined variable’ messages.
  • The ‘globalscopevar’ can be seen in the global scope and once the ‘global’ keyword has been used, the function and its loop.
  • The ‘functionvar’ can only be seen in the function and its loop.
  • The ‘loopvar’ can be seen both in the loop and surprisingly, the function too, even though its only defined within the loop. So not all scopes are completely the same.

Further reading

To learn more about PHP, you could choose to visit:


In this post we have learnt about:

  1. Variables.
  2. Functions.
  3. Scope and Globals.
  4. Reminded of where to look for error reports.

I hope you’ve progressed with your learning of PHP, next time we will continue on our journey.

Gareth Barnard
Latest posts by Gareth Barnard (see all)

Gareth Barnard

Gareth is a developer of numerous Moodle Themes including Essential (the most popular Moodle Theme ever), Shoelace, and other modules such as course formats.

4 thoughts on “The first step – part two

Add a reply or comment...