Feb9, 2009

Beginner's Guide to PHP - Part Six

Functions are the lifeblood of PHP. You can't do a lot without PHP's built-in functions, and life would get very tedious very quickly if you weren't able to define your own in a script.

Let's take, for example, one of my scripts: BellaBook. BellaBook is a flat file guestbook and so constantly writes to files. It writes to a file when you submit an entry, it writes to a file if I approve, edit or even delete an entry. There's a whole lot of file writing going on. Imagine how difficult to maintain the script would become if that file writing — which is effectively the same code — was written in 6-7 different places that you had to update each time? Well, I can tell you, because that's how it started out... boring! It got very easy to make mistakes. By creating one function with one set of code that I could then simply reference as many times as needed, I eradicated many of the maintenance problems I was having.

So, now you know the why, but what about the how?

The basic syntax for creating a function is as follows:

function myFunctionName() {

}
Functions always start with function, and should start with a letter or number (like $variables). Always try to give function names that correspond to what the function is doing, as it'll make your life easier in the long run (finding function1($var); in a script will throw up a wall, whereas you can immediately guess what multiplyBy2($var); does.) Inside the curly braces we can place the code we'll need to use.

In our simple example, we shall echo a greeting with our function. We could simply write the greeting on each page, but — going back to what I said earlier — imagine how tedious it would be to update if we wanted to change that greeting later on? So, we start with our base syntax, and our echo inside the curly braces:
function greeting() {
echo 'Good morning!';
}
You can then call this whenever you like using greeting(); (or <?php greeting(); ?> if you're not already within a PHP block). Each time you put this on page, you will see "Good morning!".

"Good morning!" isn't very useful if it's the middle of the afternoon, or if we want to specify our own greeting. To combat this limitation, we can pass a variable with our custom greeting to the function; or, if none is set, show the standard greeting. Variables are passed between the "( )" in the function declaration, like so:
function greeting($var)
So, changing our function to:
function greeting($greet) {
if (!empty($greet))
echo $greet;
else
echo 'Good morning!';
}
We can then choose to rely on the standard greeting using <?php greeting(); ?> with no variable, or specify our own: <?php greeting("Good evening!"); ?>. The data inside the quotes is available as our $greet variable inside the function.

If we were to pass two variables, e.g. function greeting($var, $var2), we would be able to provide two lots of data, e.g. <?php greeting("Good evening!", "Second bit of data"); ?>Once passed, variables can then be used inside the function as with $greet above. However, variables created or modified inside the function can not be used outside of the function. This is what's known as "scope". Take for example, this snippet of code:
$newgreeting = 'Oh hi there';
function greeting() {
echo $newgreeting;
}
If you used this code, and tried to echo your greeting by way of <?php greeting(); ?>, you'd get an undefined variable error. Because the $newgreeting variable was created outside of the scope of the function, it cannot then be used inside.

Functions are important to get right, but a pain in the bum to get used to. Practice creating your own functions using basic mathematical operators to get to grips with how function scope affects variables inside and outside of your functions. Next time, I'll try to cover global scope, and default arguments.

Tagged , , and .

Sep19, 2008

Beginner's Guide to PHP - Part Five

Back in Part Four of the Beginner's Guide to PHP, we covered the basics of arrays, and the foreach construct which is used to iterate over arrays. Today, you get to learn about for(), woot for you. According to the PHP manual, for() loops are the most complex in PHP, so I'm hoping I can break them down in a way that makes them seem nice and friendly, and without losing any important information along the way.

The Basic for Loop

The most basic of all for() loops contains three expressions: for(expression 1; expression 2; expression 3)

  • Expression 1 executes once at the beginning of the loop.
  • Expression 2 executes on every iteration of the loop (to iterate: "To say or perform again; repeat." Answers.com); if the expression evaluates to true, the loop continues, if it evaluates to false the loop stops.
  • Expression 3 executes at the end of every iteration of the loop.

So let's break the following down in to individual iterations:

for ($i = 1; $i < 5; $i++) {
echo $i;
}
...this means:Iteration 1Expression 1 executes once, sets $i variable to 1
Expression 2 checks if $i is less than 5, is true so loop continues...
Expression 3 increments $i by 1$i is now 2.Iteration 2Expression 1 does nothing, because it only executes at the very beginning of forExpression 2 checks if $i is less than 5, is true so loop continues...
Expression 3 increments $i by 1$i is now 3.

...and this continues until iteration reaches 5, where we have:

Expression 1 does nothing, because it only executes at the very beginning of forExpression 2 checks if $i is less than 5, is false, so loop stops
Expression 3 isn't executed because the loop has stopped

Complicating Matters

The complex part comes in — or in my opinion, anyway — when you start skipping over expressions. The for() loop will let you remove expressions as long as you leave the semi-colons in place. For example, if $i was set further up in the script you might have just:
for ( ; $i < 5; $i++) {
echo $i;
}
Any of the 3 expressions can be skipped, but I don't like doing this as it makes the code harder to read. I prefer having everything relevant in one place.

Oh, and Don't Forget

As if that wasn't bad enough, you can also put multiple expressions in place of one standard one, separated by commas. The PHP manual has this to say:

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

PHP for Tip:

The key to keeping for() speedy is to give expression 2 the least work possible. If, for example, the second expression is based on a calculation (such as counting an array), it might look like this: for($i = 1; $i < count($array); $++)

However, as mentioned above, expression 2 is executed each time the array is iterated over, which means $array is count()ed multiple times. To reduce the load (even though it may only be seconds) it's best practise to store the count in a variable and text against the variable instead. This can be done as part of expression 1 (for($i = 0, $count = count($array); $i < $count; $i++)) or before the loop:

$count = count($array);
for($i = 0; $i < $count; $i++) { ... }
That's it! Got it? :)

Tagged , , and .

Jun16, 2008

Beginner's Guide to PHP - Part Four

In Part Three of the Beginner's Guide to PHP we learnt about the if construct ("statement"), and using it to check the value of some input. In this guide we'll learn about two more constructs: foreach() and array()

foreach Construct

foreach — a type of loop, but we'll cover that more in the future — is a language construct created to easily iterate through arrays. Iterate is simply a posh word for doing something repeatedly; in this context, iterate refers to the process of executing a given instruction for each value in the array. foreach has two different valid syntax, similar in style but both useful in different situations:

foreach($array as $value)
do this statement

foreach($array as $key => $value)
do this statement
However, to understand foreach properly, first we need to understand arrays...

Understanding Arrays

When I was first learning PHP, it took me longer to come to grips with arrays than anything else (no idea why), so I hope that I'll be able to explain them to you without putting you all in the same predicament. An array is like a bank of values. Where a variable only stores one bit of information (e.g. <?php $variable = "data"; ?>) an array stores multiple bits — sometimes other arrays — with each value (bit of info) assigned to its own key.

Creating and Populating Arrays

An array is usually created with the array construct, like so:
<?php
$array = array();
?>
We can then populate the array with data. The easiest way of doing this is creating a comma separated list of the values we want to store inside the array(), like so:
<?php
$array = array("value", "data", "information", "stuff");
?>
When using this method, each bit of data is assigned a numerical key starting from 0 — so key 0 would contain value, 1 would contain data and so on — thus ideal for storing data that doesn't need specific keys.

Sometimes, however, we need a nice logical key for each bit of information stored. For example, let's take fast food (a subject close to my heart ;) ). We have burgers, pizzas and steak. Let's imagine that we need to store the restaurant name for each of these types of fast food, so that we can show the restaurant name without having to remember numerical keys. The data would be inserted into the array like so:
<?php
$fastfood = array(
"burgers" => "McDoogles",
"pizza" => "Pizza Barn",
"steak" => "Joe's Steak House"
);
?>
..where the desired key is specified, followed by => and then the required value. Each key/value pair is separated by a comma. I've spaced it all out in the example to make it easier to read, but there's no reason why you can't specify the data without gaps as per our numerical key array (e.g. $fastfood = array("burgers" => "McDoogles", "pizza" => "Pizza Barn", "steak" => "Joe's Steak House"); )

Back to foreach

We now have a useful array storing fast food types and the name of the restaurant associated with this food. Using echo, which we learnt about in Part Two, we could echo each bit of information from the array separately addressing it by key (e.g. echo $array['key'] where array is the name of the array, and key is .. well, the key)

...or we could go one better and use foreach to iterate over the array and echo each key/value pair automatically. This has the advantage that if we add to the array, the new data will be echoed without us having to manually add more echo statements.

To do this, we use the second foreach syntax demonstrated above (we could use the first, but wouldn't have easy access to the array key, which we need). We want to loop over the $fastfood array, echo the key (which contains our fast food type) and the value (which contains the name of the restaurant where this is available). The code for this is as follows:
foreach($fastfood as $key => $value)
echo $key . ' is available at: ' . $value . '<br>';
Put together with our earlier code:
<?php
$fastfood = array(
"burgers" => "McDoogles",
"pizza" => "Pizza Barn",
"steak" => "Joe's Steak House"
);

foreach($fastfood as $key => $value)
echo $key . ' is available at: ' . $value . '<br>';
?>
This would give us the following output:

burgers is available at: McDoogles
pizza is available at: Pizza Barn
steak is available at: Joe's Steak House

Excusing the grammatical error, we have an accurate list of fast food and the restaurant it is available from.

Just like the if construct, if we wanted to add more than one statement to execute inside the foreach, we can use curly braces:

foreach($array as $key => $value) {
do statement 1;
do statement 2;
}
And that, my dears, is foreach. Feel free to ask any questions you may have :)

Important note: in the code example I use a full stop to concatenate variables to the string within the single quotation marks. I haven't covered this in detail yet, but will get to it in one of my future guides.

Tagged , , and .

Feb12, 2008

Beginner's Guide to PHP - Part Three

I've had to restart this about 4 times now, because each time I decide to finish off, I get half way and somehow lose the file. I don't know about l33t PHP Ninja; recently I've been l33t file loser.

Anyway, quick recap: in Part Two of the PHP Beginners Guide I briefly covered the basic mathematical operators, these allow us to do sums, and the echo statement. Although there's more to the echo statement (including concatenation, echo vs. print, etc) I will touch on these later, possibly guide 4. This time we'll be looking at comparison & logical operators, and the if construct.

Comparison Operators

It's quite common in a PHP script to want to compare two things. In fact, I can't think of any script I've created that doesn't rely on some sort of comparison. The comparison operators are as follows:

==
Means: is equal to
For example: 5 is equal to 5 and will return true, but 'hello world' is not equal to 'foo bar'
===
Means: is identical to (both value and type)
For example 5 is identical to 5 and will return true, but 5 is not identical to "5" (because PHP interprets "5" with quotation marks as a string, rather than an integer)
!=
Means: is not equal to
For example: 11 is not equal to 2.56 and will return true, but 'string' is equal to 'string'
!==
Means: is not identical to (both value and type)
For example 5 is not identical to "5" or "five" and will return true, but 5 is identical to 5
>
Means: greater than
For example: 5 is greater than 1 and will return true
<
Means: less than
For example: 3 is less than 6 and will return true
>=
Means: greater than or equal to
For example: 5 is greater than 1 and will return true, 3 is equal to 3 and will return true, but 3 is not greater than 6
<=
Means: less than or equal to
For example: 3 is less than 6 and will return true, 2.4 is equal to 2.4 and will return true, but 21 is not less than 20

Comparison operators are most typically used within an if; that is, you would compare 2 items to come to a conclusion and display data or execute the next part of the script depending on the result.

if Construct (Statements)

The if construct — generally (and incorrectly, if you want to be anal) referred to as an if statement — executes depending on the result of the expression. A typical if statement looks like this:

if (expression)
statement executed if result is true;
The basic premise is that the expression contains our 'check', or conditional, and if the result is a Boolean true, the statement or following block of code is executed. (We covered Boolean values in Beginners Guide Part One.) This is where the comparison operators come in - we use these to compare two things to get our true or false.

In Part Two, we had the following section of code:
<?php
$name = "Jem";
$age = 20 + 1;
?>
We can adapt this to include our if. As I'm now 22 (a PHP guide per year?!) we can conveniently use a comparison operator to see if our age is correct:
<?php
$name = "Jem";
$age = 20 + 1;

if ($age == 22)
echo "The age variable contains the correct value";
?>
Except we know that $age is 21. To prevent an empty page from being returned, and to give our script user (you) a clue as to what's going on, we use an else statement. else extends the basic functionality of an if, and will execute if the result of the if condition is false. For example:
<?php
$name = "Jem";
$age = 20 + 1;

if ($age == 22)
echo "The age variable contains the correct value";
else
echo "The age variable contains the wrong value!";
?>
As we already know $age is 21, we should be able to easily guess that the page will now show "The age variable contains the wrong value!".

In my examples, I've only used a single echo statement after the if/else check, and therefore haven't used curly braces to separate the blocks/groups of code. If you wish to execute more than one statement, or feel you need the curly braces to visually distinguish between groups, the previous code example would look like this:
<?php
$name = "Jem";
$age = 20 + 1;

if ($age == 22) {
echo "The age variable contains the correct value";
} else {
echo "The age variable contains the wrong value!";
}
?>

Logical Operators

The three most basic logical operators, AND (&&), OR (||) and NOT (!) are also used in if statements to alter the expression and change the condition on which the statement is executed.

The NOT operator is often used before a function to reverse the result. For example, you can use is_numeric() to check whether or not a variable is numeric, thus we could place ! before it to reverse the purpose of the function (to check if it is not numeric):
<?php
$age = "heehee, we've changed this variable to a string";

if (!is_numeric($age))
echo "Uh-oh, who changed my variable? :( ";
?>
As $age is now a string, we'd see "Uh-oh, who changed my variable? :( " on the page.

AND and OR are used to check for multiple conditions. Example:
<?php
$name = "Jem";
$age = 20 + 1;

if ($name == "Jem" && $age == 22) {
echo "Our variables are both correct :) ";
} else {
echo "Our variables contain incorrect data :( ";
}
?>
Can you figure out which statement will be echo'ed on screen?

Next guide topic - err, haven't decided yet. Keep your eyes peeled and I'll try and get it up before the end of the year this time. (I know, I said that before.)

Tagged , , and .

Apr11, 2007

Beginner's Guide to PHP - Part Two

Let's have a quick re-cap of what we covered in Beginner's Guide to PHP - Part One: there are different data types (string, integer, floating point number and boolean) and variables are created by simply assigning data to them. Simple enough? Well, now we're going to take a look at mathematical operators and what we can do with them...

Mathematical Operators

'Operator' is the term used to cover various fancy symbols that we use to do stuff in PHP. (Nicely vague, right?) That is, we can use them to add integers, compare variable values, etc.. Easiest to understand are the mathematical operators — these are the kind you're used to seeing on a calculator — and are as follows:

+ Used to add two integers (numbers) together
- Used to subtract a number from another
* Used to multiply two numbers together
/ Used to divide a number from another
% Used to find the remainder after two numbers are divided from each other

At the end of Part One we also assigned data to two variables, like so:

<?php
$name = "Jem"; // this is a string
$age = 20; // this is an integer
?>
(Those of you who are really clever will have also noticed that I demonstrated a type of PHP comment without explaining what they were, but let's not pick on the inconsistencies... I'll cover PHP comments later on, when I figure out where to incorporate them. Anyway...)

We can use the $age variable we created to test our mathematical operators. Firstly, '+', because I'm not 20 anymore, so we'll want to add a year (how convenient). There are two ways to do this, and which method you choose depends on whether or not you want to retain the original value. For example, if you want to keep $age as 20 and want a new variable to store our new age, we can do this like so:
<?php
$name = "Jem"; // this is a string
$age = 20; // this is an integer
$newAge = $age + 1; // this is our age (20), plus 1 year
?>
Here we are adding 1 to our original variable. Of course, we don't need a new variable, so we might as well just add to straight to our $age variable:
<?php
$name = "Jem"; // this is a string
$age = 20 + 1; // this is an integer
?>
In reality, we all know that 20 + 1 is 21 and getting PHP to do this mundane task is a bit boring. However, it's good to understand that it's possible to do your maths homework with a script. The other mathematical operators work in the same way: $age = 20 * 5; would assign the value of 20 * 5 (which is 100) to our $age variable and so on.

Once you've created your variables and done some maths magic, you might want to display those variables to the browser. This is where the echo statement comes in handy. (There is also print, but the echo vs. print debate is long, and I use echo out of habit.)

echo Statement

echo is what's known as a simple statement. We use it to output everything inside the single or double quotation marks (...getting to that bit) or using the "here document" syntax. The contents an echo statement can span multiple lines and use infinite amounts of whitespace. BUT, the statement needs to end with a semi-colon (much like assigning variables) otherwise you get a parse error.

As I said, the contents that we want to output needs to be inside quotation marks. What you use depends on the affect you want. For example, double quotation marks will output everything — and — if there's a variable in the string you're trying to echo it will show the value of the variable (e.g. <?php echo "Hello $name"; ?> will output Hello Jem). However, if you use single quotation marks, you must 'break out' to echo a variable, otherwise all you will see is the variable name (e.g. <?php echo 'Hello $name'; ?> will output Hello $name).

Alternative to the quotation marks is the aforementioned "here document" syntax. As the PHP manual has a very good block of echo examples, I'm not going to repeat the information unnecessarily — see example 2298, echo().

Now that we've come to grips with echo and mathematical operators we can use the two to create a string of text, and output it to our browser.
<?php
$name = "Jem"; // this is a string
$age = 20 + 1; // this is an integer
echo "

My name is $name and my new age is $age

";
?>

Assuming you've copied that into a .php file and your server supports PHP as we discussed in Part One, you should see My name is Jem and my new age is 21. Magic — our first little script that outputs data to the browser.

In Part Three I will cover the other types of Operators and how they can be used (and hopefully not take 6 months to do it!)

Tagged , , and .

« Older