Welcome to the third and final installment of this series on A Complete Beginners Guide to Arrays in PHP. In part 3 we will explore some more of PHP’s built in array functions and and also look at some practical examples of using these functions by writing some useful scripts of our own. To start off with, lets look at how we might want to count the number of occurrences of a particular items value in the array. I often say ‘the item’s value’ but if it makes it easier to just refer to the array items as elements or values be my guest.
Lets say we have a basket of fruits for employees in the lunch hall. At the end of the day we count how many fruits are left in the basket. There is a function in PHP which counts the number of times a value appears in an array. For instance, if we had an array with the values ‘red’, ‘blue’, ‘red’, ‘green’, ‘red’ then the value ‘red’ would have a count of 3 because it occurs three times in the array and both blue and green only occur once so have a count of just 1.
Going back to the fruit basket example then, this is what the array looks like:
$fruits_basket = array(
"Apple", "Peach", "Banana",
"Apple", "Orange", "Apple",
"Pear", "Peach", "Apple",
"Banana", "Orange", "Banana",
"Plum", "Pear", "Banana",
"Apple", "Apple", "Orange"
);
If you care to count the occurrences of every fruit there is in this array, perhaps by hand using a tally chart you could do that and make a note. If you count each fruit carefully you should observe that Apple has the highest count, appearing 6 times in the array. You’d need to do this for each fruit until you’ve exhausted all possible fruits in this array but doing so would be time consuming and a rather laborious task. This is where the PHP Array Function array_count_values() comes in handy. This function takes as its lone argument, the array variable and returns an associative array of the form: key value => count. The ‘key value’ is the original array value held in the array and the ‘count’ value corresponds to the number of occurrences of that value in the array.
array_count_values($fruits_basket);
The above on its own will not print anything onto the screen, however since this function returns an associative array lets use it with a print_r function:
print_r(array_count_values($fruits_basket);
And we get the following output:
Array (
[Apple] => 6
[Peach] => 2
[Banana] => 4
[Orange] => 3
[Pear] => 2
[Plum] => 1 )
You may have noticed the results are not entirely in descending order as the count for Peach (2) comes before the count of Banana (4). In order to retrieve the results in descending order we could revisit what we learned in Part 2 regarding sorting arrays, and apply the sort function like so:
$fruits_basket = array(
"Apple", "Peach", "Banana",
"Apple", "Orange", "Apple",
"Pear", "Peach", "Apple",
"Banana", "Orange", "Banana",
"Plum", "Pear", "Banana",
"Apple", "Apple", "Orange"
);
sort($fruits_basket);
print_r(array_count_values($fruits_basket));
OUTPUT:
Array ( [Apple] => 6 [Banana] => 4 [Orange] => 3 [Peach] => 2 [Pear] => 2 [Plum] => 1 )
Notice now the order of the array count for values is descending, thanks to the sort function being applied.
Finding the difference in values between two arrays
Another very useful function is the array_diff() function. This function takes as its arguments, two or more arrays and compares their values. It will then return any value(s) from the first array which are not residing inside the other arrays, in other words it compares the values of the arrays and returns the difference(s):
Observe the following code snippet below:
$fruits_basket1 = array("Apple", "Banana", "Orange", "Pear", "Mango", "Lime");
$fruits_basket2 = array("Apple", "Banana", "Orange", "Pear");
In the above you can see the the first array named $fruits_basket1 contains the values ‘Mango’ and ‘Lime’ whereas the second array named $fruits_basket2 does not. Its another way of saying ‘what does the first array have that the second array doesn’t’?
To Output the difference we’d use the array_diff() function which returns the values that are not present in the other arrays. We assign the returned result of this function to a variable and can print it as shown below:
$fruits_array_difference = array_diff($fruits_basket1, $fruits_basket2, $fruits_basket3);
print_r($fruits_array);
OUTPUT:
Array ( [4] => Mango [5] => Lime )
The array_diff() function also works with associative arrays:
$nations_capitals1 = array("England"=>"London", "USA"=>"Washington, D.C.","France"=>"Paris", "Germany"=>"Berlin", "Spain"=>"Madrid", "Portugal"=>"Lisbon", "Austria"=>"Vienna", "Poland"=>"Warsaw", "Sweden"=>"Bern");
$nations_capitals2 = array("England"=>"London", "USA"=>"Washington, D.C.","France"=>"Paris", "Germany"=>"Berlin", "Portugal"=>"Lisbon", "Italy"=>"Rome", "Austria"=>"Vienna", "Poland"=>"Warsaw");
$fruits_array_difference = array_diff($nations_capitals1, $nations_capitals2);
print_r($fruits_array_difference);
OUTPUT:
Array ( [Spain] => Madrid [Sweden] => Bern )
Breaking up Arrays into smaller Arrays
Another very useful function is the array_chunks() function. Essentially all this function does is it takes an array and allows you to split it up into a number of smaller separate array chunks. The size of these chunks gets determined by the ‘size’ parameter passed into this function and the returned value of this function is a multidimensional array.
Syntax
array_chunks(array, size, preserve_key)
Here is a quick example of this function in action:
$nations_capitals = array(
"England"=>"London",
"France"=>"Paris",
"Germany"=>"Berlin",
"Spain"=>"Madrid",
"Italy"=>"Rome",
"Portugal"=>"Lisbon",
"Netherlands"=>"Amsterdam",
"Belgium"=>"Brussels"
);
From the above you can see we have an associative array named $nations_capitals, with various nations and their capital cities. Nothing fancy happening here, pretty simple. The function call is made using:
array_chunk($nations_capitals, 3);
As you can see the array function takes as a parameter the array, the size of the array chunks and there is also a third optional parameter you could use which is a boolean value to either preserve the keys of the new array chunks (TRUE) OR re-index them numerically (FALSE). If no third parameter value is given then the default value will be FALSE and all keys will be renamed numerically.
To understand what this function does, it would be a good idea to get its output. We do this by using the print_r function with the above code like so:
print_r(array_chunk($nations_capitals, 3));
Executing the above gives us this:
Array ( [0] => Array ( [0] => London [1] => Paris [2] => Berlin ) [1] => Array ( [0] => Madrid [1] => Rome [2] => Lisbon ) [2] => Array ( [0] => Amsterdam [1] => Brussels ) )
To improve readability you can see the output more clearly in the below screenshot:
Irrespective of how ever many values your array has, it will try to split them into ‘chunks’ of 3, which if you recall is the value we gave for the ‘size’ parameter. As you can see there were a total of 8 ‘key=>value’ items in our $nations_capitals array. The named keys of that array were names of nations and their associated values were their capital cities. When we applied the array_chunk function, we left out the third parameter which would indicate whether or not we wished to ‘preserve’ those original keys (the names of the nations). Since we didn’t provide that parameter, by default the function created numeric based keys instead hence the output you saw above. Notice how the last chunk contains just two ‘key=>value’ items, which makes sense seeing as we only had 8 in total, with the first inner array [0] holding 3 ‘key=>value’ items, the second inner array [1] holding 3 ‘key=>value’ items, and with the 3rd and final inner array [2] holding the remaining two ‘key=>value’ items.
If we specify the preserve_key parameter as ‘TRUE’ we will able to retrieve the original named keys as shown below:
print_r(array_chunk($nations_capitals, 4, TRUE));
OUTPUT:
Array ( [0] => Array ( [England] => London [France] => Paris [Germany] => Berlin [Spain] => Madrid ) [1] => Array ( [Italy] => Rome [Portugal] => Lisbon [Netherlands] => Amsterdam [Belgium] => Brussels ) )
Again, to improve readability we will refer to the screenshot below to see what happens when the preserve_key parameter is given a value of TRUE:
Creating a new array by merging one or more arrays
The array_merge is a useful function in that it allows us to merge one or more arrays into one new array. Its syntax is as follows:
array_merge(array1, array2, array3, …)
Lets see this function in action. Below we have a watered down version of our $nations_capitals array, this time holding 4 ‘key=>value’ items:
$nations_capitals = array(
"England"=>"London",
"France"=>"Paris",
"Germany"=>"Berlin",
"Spain"=>"Madrid"
);
Let us create another array named $nations_capitals2, in this array we will add nations from the the Far East and further afar:
$nations_capitals2 = array(
"Japan"=>"Tokyo",
"Malaysia"=>"Kaula Lampur",
"Australia"=>"Canberra",
"New Zealand"=>"Wellington"
);
To ‘merge’ $nations_capitals2 with $nations_capitals, we simply pass in both arrays as arguments to the array_merge() function and then use print_r to view the output:
print_r(array_merge($nations_capitals, $nations_capitals2));
OUTPUT:
Array ( [England] => London [France] => Paris [Germany] => Berlin [Spain] => Madrid [Japan] => Tokyo [Malaysia] => Kaula Lampur [Australia] => Canberra [New Zealand] => Wellington )
The PHP implode() and explode() functions
These two functions are opposites in terms of what they do. The first function implode() will take as its arguments, a ‘separator’ and an array. This function will convert the elements of an array into a single string. The elements will be separated using the separator given in the function call. The below exmaple demonstrates implode() in action:
$marvel_heroes_arr = array("Daredevil", "Thor", "Punisher", "Hulk", "Wolverine", "Iron Man", "Spider Man");
$marvel_heroes_str = implode(" ", $marvel_heroes_arr);
echo $marvel_heroes_str;
OUTPUT:
Daredevil Thor Punisher Hulk Wolverine Iron Man Spider Man
Notice the string above and the space between each sub-string item. This space was created when we passed in ” ” as argument to the implode function.
The explode() function does the exact opposite of what implode() does. This function will take a value of whatever the existing separator is of a given string and then convert each sub-string item it an independent array value with a numeric key as its index. The below example demonstrates this:
$quote = "‘Brevity is the soul of wit.‘ (Hamlet, Act 2, Scene 2)";
$quote_as_array = explode(" ", $quote);
print_r($quote_as_array);
OUTPUT:
Array ( [0] => ‘Brevity [1] => is [2] => the [3] => soul [4] => of [5] => wit.‘ [6] => (Hamlet, [7] => Act [8] => 2, [9] => Scene [10] => 2) )
Useful scripts using some of the concepts learned
We all know that each month has a given number of set days and that the days can be represented as ordinal numbers using their respective suffixes ‘st’, ‘nd’, ‘rd’ and ‘th’. The below script will format the day and append the correct suffix depending on the month day we’re in, i.e if the month day is 24 then it will append ‘th’ at the end, if its 31 it will append ‘st’ at the end.
If you’re confused as to whats happening in the above code snippet then don’t worry as I’ll talk you through it line by line.
The first line makes use of a function called getdate() which gets the current date/time information of the current local date/time. It returns an associative array with information of the timestamp.
To better illustrate this, we can use the print_r function to view the output of the gatedate() function:
print_r(getdate());
OUTPUT:
Array (
[seconds] => 7
[minutes] => 43
[hours] => 9
[mday] => 3
[wday] => 4
[mon] => 2
[year] => 2022
[yday] => 33
[weekday] => Thursday
[month] => February
[0] => 1643881387
)
Since we want the day of the month showing the appropriate suffix at the end of it, we need to identify which numbers from 1 to 31 end with ‘st’, ‘nd’, ‘rd’ or ‘th’. This is accomplished from the next line onward where a function called assign_ssoridinals() is declared. This function takes as its parameter the result of the getdate() function which we saved in our $my_date variable. Inside of this function we save the value of the ‘mday’ key from our associative array with the following line:
$current_month_day = $my_date["mday"];
Next, four arrays are declared inside this function which will hold the day numbers in arrays named ‘st_array’, ‘nd_array, ‘rd_array’ and ‘th_array’:
$st_array = [1, 21, 31];
$nd_array = [2, 22];
$rd_array = [3, 23];
$th_array = [4,5,6,7,8,9,10,11,12,13,14,15,
16,17,18,19,20,24,25,26,27,28,29,30];
Only three numbers in the range of 1 to 31 would have a suffix of ‘st’ and they are 1, 21 and 31 which makes sense since you can only have the 1st, 21st and 31st of a month. Likewise, only two numbers in the range of 1 to 31 could have the suffix ‘nd’ and they would be 2nd and 22nd while only two numbers in the range of 1 to 31 could have the suffix ‘rd’ which would be 3rd and 23rd and finally all the other numbers would have the suffix ‘th’ at the end of them. Our if-else conditional statement does the checking to see if the value stored inside our variable $current_month_day is in any of the arrays we declared above. If it is, we simply append the appropriate suffix to the end.
The rest of the code snippet is just the outputting of the result, notice we use the function call here and use the ‘weekday’ , ‘mday’, ‘month’ and ‘year’ keys to get at their respective values.
Leave a Reply