PHP: Build an online calendar



In the last tutorial, we covered the basics of PHP, including how the language was created and subsequently grew. Wewere also introduced to various parts of the language, such as variables, strings, integers and PHP’s internal date() function. In this tutorial, we’ll expand on those parts, but we’ll also introduce the concept of arrays and functions to make a fully working calendar.


We’ll assume that you have your Linux platform configured and serving PHP pages through your web browser, as outlined in the previous tutorial. If not, please refer to the previous article or the section titled Installing PHP on your Linux platform. So what exactly is an array? Well, to help us define this, let’s go back to the last tutorial, where we made use of a variable ($display_text) to hold a simple string message. The problem with variables is that they can hold only one piece of information at any one time. Wouldn’t it be great if we could store multiple items inside a variable? Well, this is where arrays come in.



Introducing arrays

The best way to think of an array is a special variable that holds other variables. An array allows you to hold as many items inside it as necessary (the only limitation on the size of the array is based on how much memory PHP is allocated). You can step through all the items inside an array (known as
traversing), and PHP comes with more than 70 functions, allowing you to perform certain actions on your array, such as searching inside, counting the number of items inside it, removing duplicate items, and even reversing the order.


“An array allows you to hold as many items inside it as necessary.”


There’s almost nothing to it when creating an array either: $data = array(); We have now created a new, empty array called $data.Arrays are structured using a key index and value data architecture. By default, when you add an item to an empty array, that item’s position in the array is 0. If you add another item, that item’s position becomes 1 in the array. You can also create your array with pre-populated data (if you already know what’s going to be in it). To do this, we just create the array as before, but this time we supply the data in a comma-separated list:

$data = array(‘Red’,
Orange’, ‘Yellow’, ‘Green’,
 ‘Blue’);

This is where the key system comes in to place. The way that PHP interprets this array will be as follows: 0 = ‘Red’, 1 = ‘Orange’, 2 = ‘Yellow’, 3 = ‘Green’ , 4 = ‘Blue’

As you can see, each key is associated to the value in the array. The most important part to remember is that arrays always start at key 0 and not key 1 as many might assume; it’s easy at first to forget.



Associative arrays

Arrays also have the flexibility of allowing us to specify our own keys (known as associative arrays). This helps a lot when you want to store a value against a specific key instead of having to rely on automatic indexes. Let’s say we wanted to store data about a person in an array; to do that we can do the following:

$person = array(‘name’ => ‘Mike Mackay’, ‘location’ =>
Essex’, ‘age’ => 29);

By using the associate instruction (=>), we’re telling PHP that we want to create a key called name and store the value Mike Mackay against it. You can store any data type in an array even other arrays. The way that PHP interprets our person array is how we would expect:

‘name’ = ‘Mike Mackay’, ‘location’ = ‘Essex’, ‘age’ = 29

When you want to use an array item, all you have to do is call the array and key you want: 
echo $data[0]; This echos out the word Red to the screen. To echo out the word Orange, you would simply change the key from 0 to 1. On our person array it’s just as simple  to echo the name to the screen, all I need to do is: echo $person[‘name’];



Add data to your array

If we have our existing array, but want to add more data to it, how do we accomplish that? There are a few ways in which we can do this and often it depends largely on whether your array has custom key indexes or not; but to add another item to our $data array we can simply do: $data[] = ‘Indigo’;

By supplying square brackets next to the array name, PHP recognises this action as wanting to push a value in to the array. PHP has a built-in function that does the same trick: 

array_push($data, ‘Indigo’);

This function takes a minimum of two arguments. The first is the array you want to push the data to, then any items afterwards are pushed to the end of the array. This conveniently allows you to push multiple items in to the array at once, for example: array_push($data, ‘Indigo’, ‘Violet’);

If you need only to push one item, the first method (using the square brackets) is recommended, as it has no system overheads of calling a function. If we wanted to add another item to our $person array, we need only to specify the key we wish to use, along with the required value:

$person[‘profession’] = ‘Developer’;



Arrays within arrays

As I mentioned before, an array can hold any type of item inside  this includes other arrays. The practice of multiple arrays is quite common, and you’ll find it extremely useful. Again, there are a couple of different ways of achieving this, and the one you use will be based on your array structure. For this example, let’s say we have an array of McLaren F1 racing drivers. Open up a text editor, enter the following PHP code and save it as drivers.php in your web root:

<?php
$drivers[] = array(
 ‘name’ => ‘Jenson Button’,
 ‘nationality’ => ‘British’,
 ‘championships’ => 1,
);
$drivers[] = array(
 ‘name’ => ‘Lewis Hamilton’,
 ‘nationality’ => ‘British’,
 ‘championships’ => 1,
);
?>

We’re using the square brackets to instruct PHP that we wish to push the driver data to the end of the array. Each item inside the master array() must be separated by a comma. Our $drivers array now contains two items these items are arrays of data containing driver information that we wish to display. In PHP’s eyes, the data for Jenson Button is located in $drivers[0], while the data for Lewis Hamilton is located in $drivers[1]. We could have created custom keys instead of using 0 and 1, but it’s not strictly worthwhile for this example. We could simply display the data using echo and then
specifying the array index key (such as $drivers[0]), but how would we display each item when we don’t know how long the array is? Thankfully for us, there’s a simple control function called foreach() that allows us to do this.

So you might be asking why we wouldn’t know the length of an array? Well, we know what driver data is contained in each item (name, nationality and championships), but a database query (or similar function) might return one driver, or it might return five drivers. We could get the the total number of items in the array by using a PHP function, but using foreach() is simpler and lets us write shorter code. The foreach() control gives us an easy way to iterate over an array. Using drivers.php that we’ve just created, copy the code just below the PHP block that contains the drivers array:

<?php
foreach($drivers as $driver) {
 echo ‘Name: ‘ . $driver[‘name’]. ‘<br />’;
 echo ‘Nationality: ‘ . $driver[‘nationality’]. ‘<br />’;
 echo ‘World Championships: ‘ . $driver[‘championships’].
 ‘<br /><br />’;
}
?>

When you view the file in your browser, you should see a basic list of drivers on your screen:


  •  Name: Jenson Button
  •  Nationality: British
  •  World Championships: 1
  •  Name: Lewis Hamilton
  •  Nationality: British
  •  World Championships: 1


Using a code editor that has built-in syntax checker (such as Eclipse, the
winner of our IDEs Roundup in LXF152) can save a lot of time and frustration!


On each loop of $drivers, the value of the current item is assigned to $driver (the first loop being Jenson Button), and the internal array pointer is moved on by one; so on the next loop you’ll get the next item from the array (Lewis Hamilton). This continues throughout each item in the array until the end is met. The foreach() function requires two parameters – the first is the array we want to loop through. We then use a PHP keyword as, then we enter a temporary variable name that we want to assign the loop item to (this variable is only available inside the loop). In literal terms, we’re saying: loop through each item in the $drivers array and store each driver item to a temporary array called $driver.

Hopefully, in the example you’ll recognise a few parts from the last tutorial; we’re echoing out a string concatenated by a variable  this being each bit of information about the driver in the array. We then concatenate another string which is HTML, allowing us to format the output in a basic manner. On the last array item, $driver[‘championships’], we echo out two line breaks; this just gives us a bit of separation between each driver. 

The 2012 F1 calendar we’ll be recreating with our code.




Let’s talk about functions

There are two types of functions in PHP:
1.  Built-in PHP functions, such as date() and array_push().
2.  User-defined functions.

We’ll be focusing on the second type for now (we’ve already covered a few built-in PHP functions).
A user-defined function is a special block of PHP code that we write that can perform custom operations any time it’s called. Some functions are written to manipulate data and then send that new value back, while others perform one-way operations, such as writing data to a file or inserting the data in to a database. To create a function, all we need to do is write the word function followed by the name we wish to call our function (It’s important to note that function names can only start with letters or underscores), followed by parenthesis and then a pair of curly braces:

function shout() {
}

We can also supply data, known as arguments, to our function to be used inside it. When calling this function and sending information to it, the function assigns this data to the internal variable called $text, where it can manipulate it, or do as required. This data is then held locally to the function
and does not overwrite any variables outside of it:

function shout($text) {
}

If we want the newly-modified data back, we can use return to send it back:

function shout($text) {
 return $text;
}

To call a function, all you need to do is write the function name followed by parenthesis either with or without any parameters (based on the function’s requirements): shout(); We have our basic function, but all it does is send back exactly what we sent to it - pretty pointless I’m sure you’ll
agree. Let’s make our function do something a bit more interesting. Create a new PHP file, copy the following code in to it and save it as function.php:

<?php
echo shout(‘Hello World’);
function shout($text) {
 return strtoupper($text);
}
?>

If you run that in your browser, you should see ‚‘HELLO WORLD’ being displayed. What’s happening is we’re sending a string straight to the function, where we echo the returned value out. The built-in PHP function strtoupper() has a simple purpose – take the string input and convert it to uppercase. We could modify the function to perform the echo inside instead of using return, but our original method gives us greater flexibility for multi-purpose use (we may not always want to echo a value out immediately). We could write any kind of code inside our function, and we’re not limited to doing string transformations.



If() and else()

You’ll notice something else with our code… we’ll be performing a conditional check using if() and else(). If/else provides a simple way of evaluating which code to run, based on the outcome of a particular check, or condition. If() is only executed when the condition inside the parenthesis equates (or returns) TRUE, otherwise else() is called – just the code between the curly braces is executed, but only one of them will ever be run:

if(condition is true) {
 // Run the code in this block
}
else {
 // Run the code in this block instead
}

In literal terms, all we’re going to say is: If today’s date is found as an index in the array, then echo out the race data, otherwise echo the no races message instead. Let’s now create a basic events calendar using our arrays and function knowledge. 



Put it all together

We don’t want anything over the top, so for now we’ll create an F1 2012 race calendar. We’ll send today’s date to a function and return a current race if one is happening on that day, otherwise we’ll echo out a generic message. Start off by creating a new PHP file called calendar.php, then create a function that initially holds an array of the race dates:

<?php
function is_race_day() {
 $race_dates = array(
 ‘18/3/2012’ => array(‘title’
 => ‘Australian Grand Prix’,
 ‘location’ => ‘Melbourne’),
 ‘25/3/2012’ => array(‘title’
 => ‘Malaysia Grand Prix’,
‘location’ => ‘Kuala
Lumpur’),
 15/4/2012’ => array(‘title’ => ‘Chinese Grand Prix’,
‘location’ => ‘Shanghai’),
 ‘22/4/2012’ => array(‘title’ => ‘Bahrain Grand Prix’,
location’ => ‘Sakhir’),
 ‘13/5/2012’ => array(‘title’ => ‘Spanish Grand Prix’,
‘location’ => ‘Catalunya’),
 );
}
?>

I’ve included just the first five dates of the season for now, but feel free to add more. Next, let’s update the function. Get today’s date (see the first tutorial on the date() function) and check whether it has a Grand Prix or not; for this we’ll use a built-in function, array_key_exists().


“Get today’s date and check whether it has a Grand Prix or not.”


Write the following just below the end of the array and before the functions’ closing curly brace:

$date = date(‘m/d/Y’);
if(array_key_exists($date, $race_dates)) {
 echo “Today’s race is the “ . $race_dates[$date][‘title’] . “ in “
 . $race_dates[$date][‘location’] . “.”;
}
else {
 echo “There is no race today.”;
}

We use the value of $date inside the array_key_exists() function  this function accepts two parameters: the first is the key you’re looking for (in our case it’s the date) and the second is the array you wish to check against (our $race_dates array). The array_key_exists() function returns a boolean of TRUE if the key exists, or FALSE if it doesn’t. If the race is found, we’re going to echo out the race details. We can retrieve this data because we know the key exists, therefore we use the $date variable as a shortcut to retrieve the information. Essentially, it’s the same as writing:

 echo $race_dates[‘13/5/2012’]
 ‘title’];

All that’s left for us to do is to call the script. We do this in exactly the same way as our earlier function script and put the function name (with parenthesis) at the top of our script:

is_race_day();

We can then run this script in our browsers by going to calendar.php, or we can use includes() to embed it on an existing website. If a race exists on the day the script is run, we’ll be presented with the details. To test this, simply hardcode a date in the $date variable: 

$date = ‘13/5/2012’;



And with that, we’re done!

This might all feel like quite a lot to take in at once if you’re new to arrays and functions, but hopefully you’ll see that what we’ve learnt here is extremely important and intrinsic to programming. Try modifying the calendar; you could be more specific with your dates and have something on every day of a month if you wish. As an exercise, look at the date() function and alter the calendar to echo messages based on the hour of the day. Remember, you won’t need an entry for every day  only every hour. 

In the following tutorial Mike Mackay explains how to add the functionality to dynamically select races and view details. 

Be sure you subscribe to our Newsletter below :)

Express Science Lab Engineer & Science Enthusiasm

Experience the Science of the Universe and IT Programming into a fun and creative way. Ever been fascinated about how the Universe works, about planets, Solar Systems and how to program a computer to write a code for you, ever asked yourself how a website works ? Let's find out, come step into your own laboratory of knowledge.

No comments:

Post a Comment

Shout here! Throw the pipettes, brake a Berzelius glass so we can hear you from the lab!