Welcome to part two of A Complete Beginners Guide to Arrays in PHP. Previously in Part 1, we looked at the kinds of arrays supported in PHP and how to initialise, pre-initalise these arrays. We also looked at how to access and modify the values of arrays as well as using the foreach loop to traverse through these arrays outputting their respective ‘key – value’ pair values.
Adding and Removing items from an array
Now we will look at some of the ways in which we can manipulate and work with these arrays using PHP’s built in Array functions. To start off with, I will introduce the array_shift() and array_unshift() functions. These two functions add and remove the first item of an array respectively. Let us take a look at how both these functions work and how they affect an array. We’ll use the $fruits array from Part 1 to keep consistent. $fruits consists of 4 items:
$fruits = array("Apple", "Banana", "Orange", "Pear");
PHP’s array_shift() function REMOVES the FIRST item from an array and then RETURNS the value of the removed element. So if we wish to remove the first item from the $fruits array which happens to be “Apple” then we would pass in the array as an argument to the array_shift() function and echo out the result of the function:
echo array_shift($fruits);
OUTPUT:
Apple
To observe what values $fruits holds now we can use the print_r() function, which if we you recall from Part 1, displays out the array as key / value pairs:
print_r($fruits)
OUTPUT:
Array ( [0] => Banana [1] => Orange [2] => Pear )
Notice that as this is an indexed array, the key value 0 will no longer reference the element that has the value “Apple” as its been removed from our array. Instead, the Key value 0 will now reference the element with the value “Banana”.
The array_unshift() method does the opposite of array_shift(). Instead of REMOVING the first item in an array, this function will ADD an item at the beginning of an array. Just like array_shift(), it takes the array variable as one of its arguments followed by the value of the new element to be added to the array. It’s return value is an integer, indicating the new number of elements in that array:
$fruits = array("Apple", "Banana", "Orange", "Pear");
echo array_unshift($fruits, "Peach") . "<br />";
print_r($fruits);
OUTPUT:
5
Array ( [0] => Peach [1] => Apple [2] => Banana [3] => Orange [4] => Pear )
The functions array_shift() and array_unshift() add and remove items at the beginning of an array. We can also add and remove items at the END of an array using the array_pop() and array_push() functions. The array_pop() function REMOVES the LAST item in the array and returns its value as shown below:
$juiceDrinks = array(
"Orange Juice",
"Apple Juice",
"Pineapple Juice",
"Cranberry Juice",
"Mango Juice"
);
echo array_pop($juiceDrinks);
OUTPUT:
Mango Juice
If we use a print_r() function to look at whats inside of $juiceDrinks we will see the following:
print_r($juiceDrinks);
OUTPUT:
Array ( [0] => Orange Juice [1] => Apple Juice [2] => Pineapple Juice [3] => Cranberry Juice )
If we wish to add two new fruits to the end of our $fruits array, then we use the array_push() function, passing in as arguments the array name and the values of our new array items:
$juiceDrinks = array("Orange Juice", "Apple Juice", "Pineapple Juice", "Cranberry Juice", "Mango Juice");
array_push($juiceDrinks, "Papaya Juice", "Kiwi Juice");
OUTPUT:
Array ( [0] => Orange Juice [1] => Apple Juice [2] => Pineapple Juice [3] => Cranberry Juice [4] => Mango Juice [5] => Papaya Juice [6] => Kiwi Juice )
Search for an item by its value in an array
A very common and very useful function is the in_array() function. This function simply searches for an item in an array by its value and returns a boolean value of TRUE or FALSE depending on whether that item is found:
$colors = array("Red", "Blue", "Green", "Yellow");
$findColor = "Purple";
if(in_array($colors, $findColor)) {
echo "$findColor is in our array";
} else {
echo "$findColor not found in our array";
}
OUTPUT:
Purple not found in our array
In our above example we actually stored the value of the item we were looking for in a variable named $findColor. We needn’t have to do this, we could just as easily pass in a string argument into in_array(), however when we echo out the result of our search we need to manually type the item value as part of the output:
$colors = array("Red", "Blue", "Green", "Yellow");
if(in_array($colors, "Purple")) {
echo "Purple is in our array";
} else {
echo "Purple not found in our array";
}
OUTPUT:
Purple not found in our array
Counting the number of items in an array
In order to count the number of items (elements) in an array we can use a PHP function called count():
$fruits = ["apple", "banana", "orange", "pear"];
echo "There are " . count($fruits) . " elements in the \$fruits array.";
OUTPUT:
There are 4 elements in the $fruits array.
Sorting Arrays in PHP
This section is going to look at the various ways we can sort arrays using the ‘sort’ functions in PHP. The first function I’m going to demonstrate in action is the sort() function which sorts the values of the elements in ascending alphabet or numerical order depending on the elements value data type:
$nations = [
"USA",
"France",
"Japan",
"Croatia",
"Netherlands",
"Spain",
"Australia",
"England"
];
sort($nations);
print_r($nations);
OUTPUT:
Array ( [0] => Australia [1] => Croatia [2] => England [3] => France [4] => Japan [5] => Netherlands [6] => Spain [7] => USA )
As you can see from the above, using the print_r() function we can view the result of applying the sort() function on our array of nations. The nations are now sorted in alphabetical order next to their numerical key values.
The sort() function has a counterpart that does the reverse action on an arrays elements. The function rsort() will sort the values of the array elements in descending alphabetical/numerical order:
$nations = ["USA", "France", "Japan", "Croatia", "Netherlands", "Spain", "Australia", "England"];
rsort($nations);
print_r($nations);
OUTPUT:
Array ( [0] => USA [1] => Spain [2] => Netherlands [3] => Japan [4] => France [5] => England [6] => Croatia [7] => Australia )
We can also sort associative arrays using the functions asort() and ksort(). The asort() function will sort an associative array in ascending order based on its elements values whilst the ksort() function will sort an associative array in ascending order based on its key values.
The asort() function in action:
$studentScores = [
"Martin"=>78,
"James"=>56,
"Shruti"=>81,
"Hector"=>90,
"Samuel"=>67,
"Denise"=>59,
"Maria"=>62
];
asort($studentScores);
foreach($studentScores as $studentName => $studentScore) {
echo $studentName . " - " . $studentScore;
echo "<br />";
}
OUTPUT:
James - 56
Denise - 59
Maria - 62
Samuel - 67
Martin - 78
Shruti - 81
Hector - 90
Notice how the students have been shown based on lowest scores all the way down to the highest, these elements of our associative array $studentScores have been sorted in ascending order based on their values and not their keys.
Perhaps we’d like to do the opposite and view the student scores from highest to lowest, in which case we will need to perform an array sort in descending order based on their values. We can achieve this using the arsort() function.
The arsort() function in action:
$studentScores = ["Martin"=>78, "James"=>56, "Shruti"=>81, "Hector"=>90, "Samuel"=>67, "Denise"=>59, "Maria"=>62];
arsort($studentScores);
foreach($studentScores as $studentName => $studentScore) {
echo $studentName . " - " . $studentScore;
echo "<br />";
}
OUTPUT:
Hector - 90
Shruti - 81
Martin - 78
Samuel - 67
Maria - 62
Denise - 59
James - 56
We can also sort associative arrays in ascending order by the value of their keys using the ksort() function:
$studentScores = ["Martin"=>78, "James"=>56, "Shruti"=>81, "Hector"=>90, "Samuel"=>67, "Denise"=>59, "Maria"=>62];
ksort($studentScores);
foreach($studentScores as $studentName => $studentScore) {
echo $studentName . " - " . $studentScore;
echo "<br />";
}
OUTPUT:
Denise - 59
Hector - 90
James - 56
Maria - 62
Martin - 78
Samuel - 67
Shruti - 81
To sort the $studentScores array in descending order by their keys we’d use the krsort() function which we’ll skip for now but do have a play around with these functions yourself in order to better understand them. In the third and final part of this primer on arrays, we’ll look at some more functions that allow us to do some interesting things with array data and even using arrays to help us solve problems so do take a look once you’ve read through this article.
Ryan Gosling says
I’ve really enjoyed reading this second part of the arrays tutorial, your explanations and examples are really good and easy to follow and I’ve understood thanks to you. Would love to see more articles from yourself sir.
Manoj says
Dear Ryan Gosling,
Thank you so much for your kind words! I’m thrilled to hear that you enjoyed the arrays tutorial and found the explanations and examples helpful. Your encouragement means a lot, and I appreciate your feedback. I’m certainly planning to create more articles, and I’ll do my best to deliver content that’s both informative and easy to follow. If there’s a specific topic you’d like me to cover or any suggestions you have, feel free to let me know. Thanks again for your support!