Chapter five in “PHP The Good Parts” (MacIntyre, Peter B. PHP: The Good Parts. USA: O’Reilly, 2010) explained how those multicompartmental data holders called arrays are constructed and provided a sampling of a number of useful PHP array functions. So what shall the artsycoder do to learn how they all work? Why build another PHP web app of course! With HTML5 surrounding the PHP and a little CSS3 thrown in for good measure…
I call this one “Daily Fortune”. It defines two indexed arrays for creating some lucky numbers, and an associative two-dimensional array of keys and indexed array values to define the remaining fortune data. This data is then magically whipped up into a random”ish” fortune, using PHP array functions extract
, sort
, count
, shuffle
, array_rand
, array_walk
, array_splice
and array_unique
as well as the foreach
flow control structure.
Let’s delve into the mystical, magical code behind this simple one-page web app!
There are two files involved in this app:
php_arrays_web_app.php
– PHP page
php_arrays_web_app.css
– CSS for the PHP page
php_arrays_web_app.php
We start off with some standard HTML5 code to set up our page, include our CSS file and provide some introductory information, very similar to the PHP strings app.
Next we set up our form. This form will use the POST
method on the server to submit the form and call the PHP file once more. Just in case the daily fortune is not to your liking and you want to try again! Most of our form is taken up by a big chunk of PHP code.
After our PHP, we have a submit
input tag to submit the form and we finish off our HTML5 to complete the page.
Let’s focus this post on that big PHP area of the code.
There are four main sections in this PHP code:
- the
changeNumber
function, which we’ll return to in a little bit - declaration and definition of a number of variables and array data
- determining the fortune text
- determining the lucky numbers
- writing of the fortune to the page
First, we create an empty array that will store the final values for each of the portions of the fortune text, called $fortuneArray
. Next we create some arrays to store our final fortune paragraph, $fortune
, and our final string of lucky numbers, $luckyNumbers
.
Next, we define our data with which to create our fortune. $luckyNumbersArray
shows how an indexed array can be defined in PHP. Basically, each container in the array is referenced by a sequential number starting with 0. I popped some numbers into the array spots in increasing order to be our base lucky numbers.
Following this array is an associative array called $fortuneOptionsArray
, where we define a few different options to choose from for each of our fortune text sections. Associative arrays use a word as an index, which works out great for us in this case as we can logically separate our fortune info – the type of day the person will have (dayType
), the color they may wear today (colorType
) – etc. This array is also two-dimensional, because each index points to another array, storing the options for that fortune text section, such as “blue”, “yellow” etc. for colorType
.
<!--?php $fortuneArray = array(); $fortune = ""; $luckyNumbers = ""; $luckyNumbersArray = array(0 =--> 1, 1 => 2, 2 => 3, 3 => 5, 4 => 11, 5 => 13, 6 => 27, 7 => 32); $fortuneOptionsArray = array( 'dayType' => array(0 => 'a good', 1 => 'a great', 2 => 'an interesting', 3 => 'a fun'), 'colorType' => array(0 => 'blue', 1 => 'yellow', 2 => 'green', 3 => 'orange'), 'luckType' => array(0 => 'change', 1 => 'improve', 2 => 'increase', 3 => 'stay the same'), 'timeType' => array(0 => 'morning', 1 => 'afternoon', 2 => 'evening', 3 => 'night'), 'clearType' => array(0 => 'seagulls', 1 => 'squirrels', 2 => 'elephants', 3 => 'sasquatch'), 'tellType' => array(0 => 'they are awesome', 1 => 'they rock', 2 => 'they are the best', 3 => 'they are a good friend')); ...
Alrighty, the next part we will look at is the determining of the final data for our fortune text.
First, we call the PHP extract
function on $fortuneOptionsArray
.
So now we have variables at our disposal called $dayType
, $colorType
etc. with the array data from $fortuneOptionsArray
assigned to each.
Next, we use foreach
to run through each of the keys in $fortuneOptionsArray
. Line 34, we use a little PHP coding trick I found up surfin’ the web to take the $key
(for example dayType
) and make it into a variable ($dayType
) so we can get the value of that extracted variable and then assign this array data to a new variable, $extractArray
. Then we choose a random value out of this array with array_rand
and assign it to our $fortuneArray
to use later. Voila! We have stored our randomly chosen values for our fortune text – “a good”, “yellow”, “sasquatch”, etc.
Note, line 36 also shows how you can add a value to the next sequential spot in an array!
array_rand – returns a random key or keys (if key points to another array) from an array
// extract the fortune values into variables extract($fortuneOptionsArray); // choose a random value for each part of the fortune foreach(array_keys($fortuneOptionsArray) as $key) { $extractArray = $$key; $randVal = $extractArray[array_rand($extractArray)]; $fortuneArray[] = $randVal; }
On to the assigning of the lucky numbers, arguably the most complex section of the PHP. We call the bulk of the array functions here to give our lucky numbers a quite unique listing each time.
First, we perform the array_walk
function which calls the function changeNumber
on all of our base lucky numbers.
Now that we’re back to changeNumber
, let’s see its code:
function changeNumber(&$value) { $luckyNumberChangeArray = array(0 => 1, 1 => 5, 2 => 7, 3 => 10, 4 => 25); $changeFactor = $luckyNumberChangeArray[array_rand($luckyNumberChangeArray)]; $value += $changeFactor; }
The call to this function first of all passes in the value from the $luckyNumbersArray
by reference, which you may remember from my post on PHP variables and scope, means when we change it’s value in this function, it will change it back in our main program. We define a new array $luckyNumberChangeArray
with again a list of four somewhat random numbers in sequential order. We select one of these randomly using code we have already seen in the next line, and add this randomly selected number to our value.
// add a random value from an array to each lucky number array_walk($luckyNumbersArray, 'changeNumber');
So at this point, our $luckyNumbersArray
is probably a mix of numbers out of sequential order. Some may even be duplicates now!
Back in our main code, we’ll call the function array_unique
to get rid of those duplicates.
// remove any duplicate numbers from the array $luckyNumbersArray = array_unique($luckyNumbersArray);
But wait, we need a very lucky number – let’s randomize our current array and take it off the end by first calling shuffle
on the array and then using array_splice
. The latter also uses the count
function result subtracted by 1 to get the index of the last element in the array. array_splice
returns an array in this case, so we take the first element of the array to be our very lucky number.
array_splice – in simplest form, removes and returns an element from an array
count – returns the total number of elements in an array
// randomize the lucky numbers array shuffle($luckyNumbersArray); // assign the extra lucky number to be the last in the array $lastLuckyNumber = array_splice($luckyNumbersArray, (count($luckyNumbersArray) - 1)); $lastLuckyNumber = $lastLuckyNumber[0];
Finally, we use sort
to organize our main lucky numbers into sequential order, and then foreach
(with a slight twist this time, running through keys and values instead of just keys) to insert commas between them after the first lucky number. We lastly store them in our string $luckyNumbers
.
// sort the remaining lucky numbers in order sort($luckyNumbersArray); // create the string of lucky numbers from the array foreach ($luckyNumbersArray as $key => $value) { if ($key != 0) { $luckyNumbers .= ","; } $luckyNumbers .= $value; }
Finally – finally! – we organize our fortune text array values with the additional text into our $fortune
string, and echo
it with our lucky numbers for the world to see.
// create the fortune to be displayed $fortune = "<div id=\"fortuneHeading\">Daily Fortune</div><br>Today will be <strong>" . $fortuneArray[0] . "</strong> day. If you wear the color <strong>" . $fortuneArray[1] . "</strong> your luck will <strong>" . $fortuneArray[2] . "</strong>. The best time of day to get work done will be <strong>" . $fortuneArray[3] . "</strong>. Stay clear of <strong>" . $fortuneArray[4] . "</strong> and tell someone today that <strong>" . $fortuneArray[5] . "</strong>."; echo "<div id=\"fortune\">" . $fortune . "<br><br>" . "Your lucky numbers today are: <strong>" . $luckyNumbers . "</strong>.<br>Your extra lucky number is: <strong>" . $lastLuckyNumber . "</strong>.</div>";
php_arrays_web_app.css
Some simple CSS rounds out our web app by providing some body style and a style for our displayed fortune.
Notice the bit of CSS3 to display rounded corners? We use -moz-border-radius
for Mozilla browsers (Firefox) that support it and border-radius
for the rest (that support it – otherwise, they will see square corners).
body { background-color: #ffffff; font-family: Arial, Sans-Serif; font-size: 12px; max-width: 600px; } #fortune { padding: 20px; border: 2px solid #4c4b58; -moz-border-radius: 20px; border-radius: 20px; background-color: #ffffff; color: #000000; max-width:400px; } #fortuneHeading { font-size: 14px; font-weight: bold; width: 400px; text-align: center; }
Thanks for reading, I hope you have good fortune in your coding journey!