Visit the Official PHP Website
By James N Hitz
Five more Functions
To begin our explanation of the code, let me first discuss the new functions that we have introduced in this code. These functions are:
unset is used to destroy a variable. If you have a very large variable, it consumes a lot of your computer's RAM. This in turn compromises the speed of code execution and overall computer performance. So when you have a very large variable and you are through with it, you may want to unset it so that RAM is reclaimed.
The syntax for using unset is:
unset() can be used to destroy one variable or a set of several variables... even an array variable. Where multiple variables are to be unset, separate them with variables:
unset($allFile, $items, $datafile);
reset() is different from unset(). We use reset() to "rewind" the array. There is a logical pointer that points to the current record in an array (think of it like the cursor on a given line in your word processor).
reset() is used to rewind this "cursor" back to the beginning of the array. The syntax for reset() is:
In our example, we have used it to rewind the $allFile array. This was un-necessary though!
There is time when you may want to terminate a program before it matures to completion. In PHP, you can do this using the exit() function.
In our code example, we are using the exit() function to terminate the program every time we validate the entered details and find them to be wrong.
The syntax for exit() is simply:
... no return value, no arguments. This function is very similar to die()
die() works like exit() - it terminates the program. The only difference between them is that, die() can also display a message on it's way out. Our example above shows how we can display a message and then exit(), and also how we can display a message as we die()... Ouch!
The syntax for die() is:
When you die you want to DIE("This is why I've died").
Finally there is preg_split(). preg_split() belongs to the previous lesson. I just thought a reminder is in order. preg_split() will normally accept a delimiter and a string.
It then splits the string at all points marked with the delimiter - creating an array. The syntax for using preg_split is:
$array = preg_split("/delimiter/", $string_to_split);
Remember we had saved our data as:
first name|last name|email address
In our example, we are using the preg_split function to split this data at the points marked with the pipe (|) - creating an array ($items in our example):
$items = preg_split("/\|/",$line);
After this we can then reference a specific array element where:
Fine. Let's start the code from the top.