Recent Blog Posts from Andrew McCrea
Andrew McCrea's Blog Categories
Andrew McCrea's Blog Archives

Basic Programming Concepts You Can Probably Understand: Arrays



October 12th, 2012

Arrays are kind of similar to variables, but they’re more like a souped up version. They are lists of related variables. We’ll stick with setting up an array and sorting it easily with a built-in function.

Where would we see arrays being used in a game like Super Mario Bros. Wii? Possibly in the matching game between rounds.

In this case, the array might contain values for the symbol on the back of each card. These symbols might be the fire or ice plant.

Keeping in mind that a variable can hold any value and we can name them whatever we want, we create an array with this line of code:

$matching_game_cards = array();

Now we can throw values in each array. This is where arrays differ. Instead of assigning the value of a variable like this:

$match_game_cards = ‘fire plant’;

We would number the value in the list, starting with zero like this:

$match_game_cards[0] = ‘fire plant’;

Now, we could assign a whole bunch of values, knowing that we need (for this example) 4 fire plants, 4 ice plants, and 4 Bowsers, like this:

$match_game_cards[0] = ‘fire plant’;
$match_game_cards[1] = ‘fire plant’;
$match_game_cards[2] = ‘fire plant’;
$match_game_cards[3] = ‘fire plant’;
$match_game_cards[4] = ‘ice plant’;
$match_game_cards[5] = ‘ice plant’;
$match_game_cards[6] = ‘ice plant’;
$match_game_cards[7] = ‘ice plant’;
$match_game_cards[8] = ‘Bowser’;
$match_game_cards[9] = ‘Bowser’;
$match_game_cards[10] = ‘Bowser’;
$match_game_cards[11] = ‘Bowser’;

Now, we know we have all the symbols we need, but outputting them in that order is super boring and predictable. You could beat it every time. We have to sort it randomly. Luckily in PHP, you can accomplish this by putting the name of your array into one line of code.

We’ll sort the cards randomly in PHP like this:


That’s it. The order would be completely random.

The output of ‘echo $match_game_cards[0];’ could be ‘Bowser’, ‘fire plant’, or ‘ice plant’ (without the quotations).

There are also a few other built in functions instead of shuffle, including sort, krsort. Each of these functions sort by value (numerically and alphabetically), or key reverse sort, respectively, which would make the array start at 11 and count backwards to 0.

If you’d like to see all the things you can do to an array with only one line of code, check the PHP Manual for this section. There are hundreds of functions, even different examples provided by the Internet in the comments under each section.

The PHP Manual is available as an interactive website here.

Leave a Reply