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.

Disastrous Day

I’ve had a heavy workload for the past few weeks which means work has been quite hectic — and the reason why I’ve not been online in the evenings of late — but today was particularly ridiculous.

Within 10 minutes of getting into work, I had a dead system on my hands. The Dell we use for our internal job/client/supplier management system had managed to corrupt itself. To be honest, it’d been giving system errors since I started nearly 2 years ago so it’s done well to hang on this long, but it couldn’t have picked a worse moment to bomb out on me.

I managed to get into Windows and recover data, so only time was lost, but I can’t believe it took me most of the day to get it back into a fit state. I spent a good hour trying to figure out how I was going to get the right drivers without a) knowing the individual hardware component info and b) no working ‘net (because the network adapter wasn’t configured) only to discover that Dell has an excellent driver/support system. I entered in the service tag and got the full list of drivers despite the system being plenty old. Well impressed there.

Reinstalling XAMPP was quick and painless as ever, but the SQL backup was so large it kept timing out. In the end I managed to split it up into chunks and get everything back in that way, but God knows I wish I’d remembered about BigDump.

On top of all that, I managed to injure myself 4 times. I smacked my arm on the door of a colleagues car, and my knee on the dashboard (low dash, long legs). I then cracked my head on the underneath of my desk as I was plugging my KVM back in, and as I instinctively pulled my away from the desk I walloped the side of my face/eye into the corner of my PC. I seem to have escaped the black eye, thankfully.

I need a holiday, and vodka. Not necessarily in that order.

Handling the Critics

I learnt a long time ago that if you have an opinion, any opinion, there’s always going to be someone who disagrees. If you have a strong opinion, there will be even more people who disagree. The louder you voice it, the more people will find reason to criticise it. Of course, this is not always such a bad thing, because without those opposing voices I think we’d become self-obsessed, finding it hard to develop ourselves and our beliefs. Nonetheless, there are times when handling the critics can be difficult work. If you’ve ever struggled to move past someone’s opinion, here’s a few ways I use (mostly apply to web-based critique).

Don’t Take it Personally

Unless someone is attacking you as a person, don’t take criticism personally. When someone says “oh jeez, your website is far too narrow” that doesn’t mean “wow, you’re really bloody ugly”, it simple means your website is too narrow. Obvious, no? Distinguish the facts and work with that.

Take Context Into Consideration

Not all critics are interested in providing feedback that they’ve thought through. Take for instance the average response to a Pants Award: “you’re just jealous, your website sucks”; this is a typical knee-jerk reaction and doesn’t contain any information that you can apply to improvement. On the other hand, telling someone who’s never heard of you before to “piss off” because they’ve provided you with detailed paragraphs explaining their dislikes and difficulties is probably not the best way to approach criticism.

Understand Their Motive

Imagine someone sends you a list of faults and then tells you to use their product or commercial solutions to fix it all. Is that structured criticism or an advert? If the critic is gaining from any potential improvements, bear that in mind. Look elsewhere for impartial advise from those not trying to drum up business.

Grow a Thick Skin

Last but not least, grow a thick skin and get over it. Nobody is going to like you or your website/artwork/writing/whatever 100% of the time. You’re never going to have every single person alive supporting everything you do. Destroying yourself over critique, irrelevant of how correct and true it may be, is not going to bring you any happiness. Be all you can be and disregard people who expect anything more.

Of course, it goes without saying that I am the l33test ninja of all and therefore all of my advice and criticism is gospel. Ignore it at your peril. :lol:

A Furry Purry Update

As I’m being pestered left, right and centre for updates on my furry buggers, I figured I should probably blog about them. Plus I know some of you only come here for the pictures :P

Fudge settled in rather rapidly, which surprised me given the situation we rescued him from. I expected him to be timid, like Hex, but is in actual fact a little terror. He is incredibly energetic, and loves to pick on Hex then squeal bloody murder trying to pretend he’s the victim. Just last Saturday he was launching from Karl onto Hex’s head as we were lying in bed (lazy lie-in!)

fudgey

Read the rest of this entry »

CrossworDS Game Review

I’ve been a fan of word games since I was a kid. I remember going to my Nan’s and hiding away in her back room with her Take a Break mag and a pencil so that I could do the puzzles and then rub the answers out so I wouldn’t spoil it for her. So as you can imagine, when I saw CrossworDS in the GAME pending release list, I was pretty quick to put it on pre-order.

I wish I hadn’t bothered. The game is crap. The box itself advertises “over 2700″ puzzles, and yet the inner booklet keeps referring to only 555. Turns out that there is only 555 puzzles, but offered in 5 languages which is what makes the box-total. I don’t know about you, but I’ve not got the time to learn a new language just so that I can do the puzzles all over again.

This wouldn’t be so bad — over 500 crosswords is still enough to keep me busy — but the puzzles are all identical. There are a 3 difficulty levels, which in actual fact only affect the size of the puzzle ‘board’, but otherwise seem to have nothing to distinguish them from one another. The same clues are simply placed in a different order/position for each puzzle. The clues themselves are often misspelled (”1983 Nobel price Peace” — shouldn’t that be prize?) and focus on 3 distinct groups of question of which I don’t know the answer. Still, if you know the names of all of the Nobel prize winners, the names of all the rivers in Europe, and an extensive knowledge of celebrities, you’d do fine.

As if dodgy clues and box-based lies weren’t enough, the game itself doesn’t actually work! I started selecting Medium difficulty puzzles at random, only to end up on Easy boards. Every time I selected screen-based keyboard input instead of handwriting it forgot my preference, and if you exit a puzzle and go back in it loses your words, despite being advertised as saving them (if you continue the same puzzle).

I think I’ll be trading this one in for something else.