An array is an orderly arrangement of a collection of multiple values, that is the basic explanation I can up with. You can think of them as a collection of values stored in a specific variable, and also provides a way to access the value.
Indexed Arrays
A simple analogy of understanding how array work is picturing a single door storage cabinet, here is what it looks like:
The above cabinet has 6 shelves, so, let's imagine that you can store items on each shelf, so, for example, you might have a book on the first shelf, a cloth on the second shell, electric bills on the third shelf, and so on.
You might not be thinking about this, but the way you put them in, is the way it comes out, for example, a book was placed on the first shelf, so, to take it out, you gonna go to the first shelf, you won't go to the second shelf nor would you go to the third shelf, they are orderly arranged, which is the way it works in an array.
Unlike the cabinets here, there is no limit to the shelves you can have in an array, you can have millions of them, each shelf can contain anything that a variable can contain, be it a string, empty, a number, and even another array (nested array).
There are two ways you can define an array in PHP, the old way is using array(); and the new way is a square-brackets []; I'll stick with the old way.
As it is now, our arrays are empty, so, let put in some numbers into the array:
<?php
$myVar= array(4,8,15,16,23,42);
Just like the cabinet analogy, $myVar would be the cabinet, since that is the place we are storing our array items, the position you put the array items are the shelves, and they are going to stay in that exact order, so that way, we can retrieve them by the position of how that are arranged, seems easy right!
Before we go about retrieving them, I want you to note that by default, array indices start at zero, this is also called a Zero-based array indexing, it is a way of numbering the items in an array such that the first item of it has an index of 0. So, if want to output the first item in the array, we would query the number 0, which would then return 4 in our case, and if we query index 1, it would retrieve 8. let's see an example:
<?php
$myVar= array(4,8,15,16,23,42);
?>
<?php echo $myVar[0]; # The output of this is: 4 ?><br>
<?php echo $myVar[1]; # The output of this is: 8 ?><br>
<?php echo $myVar[2]; # The output of this is: 15 ?><br>
<?php echo $myVar[3]; # The output of this is: 16 ?><br>
So, make sure you understand this, the first item in an array would be referred to by using the index zero, like the cabinet example, an array can contain anything a variable can contain, let's see an example:
<?php
$myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8));
In the above array, we have a string, a number, and also a nested array which also contains a couple of items (string and number), it doesn't matter what data type you are putting in the array, just make sure they are a valid data type.
To retrieve "Pascal" you simply refer to number 2, e.g
<?php
$myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8));
echo $myCollection[2]; ?><br>
# Output is: Pascal
But how do we query the nested array, if you reference number 3, then you might be correct, just that PHP would give you a notice in the line of "PHP Notice: Array to string conversion in", this is because it tries to use array to string conversion rather than it giving us the entire output of the nested array.
Before I show you how you can query the nested array, let me show you a print function that can output information in an array nicely, it is actually used when debugging stuff in array, this is how it works:
<?php
$myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8));
?>
<?php print_r($myCollection); ?><br>
#
# Output:
#
Array
(
[0] => James
[1] => 55
[2] => Pascal
[3] => Array
(
[0] => a
[1] => b
[2] => c
[3] => 8
)
)
Look how nicely it prints the informations, we know what is what, so to pull data out of the nested array, we call the actual array position, which is [3], and we then call it's children, e.g [0], [1], [2], etc, the below is an example:
<?php
$myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8));
?>
<?php echo $myCollection[3][3]; ?><<br>
# Output is 8
If you take a look at the output we had when we used the print_r, you'll see that it nicely correlates, so, whenever you are having an issue with nested array, you can simply pull up the print_r function to see the bigger picture.
Note: The nested array is also called a multi dimensional array, so, I won't cover that anymore in this guide.
You can also replace a value in an array, if I want to replace "Pascal" with "Faruq", I simply note the position where "Pascal" is placed, in this case it is number 2, I then use an assignment operator, e.g:
<?php $myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8)); ?> <?php $myCollection[2] = "Faruq"; ?>
You can inspect it with the print_r function, and you'll see it has been replaced. You can add any item in the array even if it isn't already there, e.g, to add something in position 7, I do:
<?php
$myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8));
?>
<?php $myCollection[7] = "cat"; ?>
<?php print_r($myCollection);?>
#
# Output:
#
Array
(
[0] => James
[1] => 55
[2] => Pascal
[3] => Array
(
[0] => a
[1] => b
[2] => c
[3] => 8
)
[7] => cat
)
As you can see, it just added it for us, this isn't actually an ideal method if you simply want to go to the end or you don't know how long the numbers are, in that case, you can make a blank, it would then append it to the end of wherever the last index is, e.g:
<?php
$myCollection = array("James", 55, "Pascal", array("a", "b", "c", 8));
?>
<?php $myCollection[] = "cat"; ?>
<?php print_r($myCollection);?>
#
# Output
#
Array
(
[0] => James
[1] => 55
[2] => Pascal
[3] => Array
(
[0] => a
[1] => b
[2] => c
[3] => 8
)
[4] => cat
)
Arrays are a superb solution if you have numerous items, e.g, if you want to create a thousand usernames, you wouldn't want to create a thousand variables, we can simply assign all of them to an array, and then use one easy-to-reference variable to pull up each username by its index.
Another good thing about an array is whatever you put in an index, stays in that index, so, an array is good for orderly arranged items, if you like, you can sort the order by numeric or alphabetically, whatever you want, is possible with an array.
Associative Array
An associative array is an object-indexed collection of object, it is similar to the indexed-array but in the associative array case, it is an object indexed unlike an indexed-array that is integer-indexed, it is fairly similar, we associate them with a label, so whenever we are querying the array, we use the label. It doesn't really make sense to use a indexed-array when storing the information about your user, but when we use an associative array, we can label then by Name, Age, Phone Number, and the likes, I guess you get the idea.
Just like the cabinet analogy, assume each of the shelves has it's own door with a label to identify the shelf, we call the label on each of the shelves the key, and whatever we store in the shelf the value. The combination of this is referred to as the key-value pair, so, looking at the cabinet with multiple doors, we would have a series of keys and values that make up the associative array.
Here is an example of associative array:
<?php $userInfo = array("first_name" => "Pascal", "last_name" => "Faruq"); ?>
<?php echo "First Name is: " . $userInfo["first_name"]; ?><br>
<?php echo "LastName is: " . $userInfo["last_name"]; ?><br>
#
# Output:
#
First Name is: Pascal
Last Name is: Faruq
What I did there is added the key or the label which are first_name and last_name, I then added the values of both of them, you can have more of those, e.g email address, and the likes.
That is what an associative array looks like, so, whenever you want the value of the first name, we query the label "first_name", and if you want the last name, you call the "last_name", here is another way you can format the associative array, and don't forget that they are separated by a comma(,):
<?php $userInfo = array("first_name" => "Pascal",
"last_name" => "Faruq",
"email_address" => "devsrealmer@mail.com"
);
This looks nicely structured!
You can change a value of an array by using an assignment operator, e.g:
<?php $userInfor["first_name"] = "James";?>
This would change the first_name value to "James", also, just like the indexed-array, you can add a key-value pair even if it isn't already there, e.g, to add a key-value pair of phone_number, I'll do:
<?php $userInfo = array("first_name" => "Pascal", "last_name" => "Faruq", "email_address" => "devsrealmer@mail.com" ); ?> <?php $userInfo["phone_number"] = "00-000-00-00"; ?> <?php print_r($userInfo);?> # # Output: # Array ( [first_name] => Pascal [last_name] => Faruq [email_address] => devsrealmer@mail.com [phone_number] => 00-000-00-00 )
I'll conclude this section with the following example:
<?php $myCollection = array(0 => "James", 1 => 55, 2 => "Pascal"); ?> <?php print_r($myCollection);?> # # Output: # Array ( [0] => James [1] => 55 [2] => Pascal )
You can see in fact that associative array and the indexed-array are the same, the only difference is PHP handles the key for us in a indexed-array while we handle the key for ourselves in an associative array, so, the above example mimics how it would be done in a indexed-array, no difference whatsoever.
So, whenever you want to describe the meaning of a value, use an associative array, and if you just want to store multiple items without describing the meaning, use an indexed-array, and PHP would handle the indexes for you.
Array Functions
Just like any other type, there is always a function that can do magic to the type, there are lots of them in array, so, here are an example of the major ones:
Example 1: sort() - This functions sorts an array.
<?php $num = array("5", 8, 6, 9); # # Example 1: Sort Number # sort($num); print_r($num); ?><br> # # Output: # Array ( [0] => 5 [1] => 6 [2] => 8 [3] => 9 )
Example 2: rsort() - Sort an array in reverse order
<?php
$num = array(5, 8, 6, 9);
#
# Example 2: reverse Sort Number
#
rsort($num); print_r($num); ?><br>
#
# Output:
#
Array
(
[0] => 9
[1] => 8
[2] => 6
[3] => 5
)
Example 3: shuffle() - Shuffle an array
<?php
$num = array(5, 8, 6, 9);
#
# Example 3: Shuffle Number
#
shuffle($num); print_r($num); ?><br>
#
# Output
#
Array
(
[0] => 6
[1] => 9
[2] => 8
[3] => 5
)
The above would give you different output on each run.
Example 4: count() - Count all elements in an array, or something in an object
<?php
$num = array(5, 8, 6, 9);
#
# Example 4: Count all element in the array
#
echo count($num); ?><br>
#
# Output:
#
4
Example 5: max() - Maximum Value in an array
<?php
$num = array(5, 8, 6, 9);
#
# Example 5: Maximum Value in an array
#
echo max($num); ?><br>
#
# Output
#
9
Example 6: min() - Minimum Value in an array
<?php
$num = array(5, 8, 6, 9);
#
# Example 6: Minimum Value in an array
#
echo min($num); ?><br>
#
# Output:
#
5
Example 7: imlode() - Join array elements with a string or returns a string element from ana array.
When using the implode function, you use specify what to put between the array elements. Default is "" (an empty string), let's use a comma:
<?php
$num = array(5, 8, 6, 9);
#
# Example 7: Implode
#
echo implode( ", ", $num); ?><br>
#
# Output:
#
5, 8, 6, 9
You can use whatever divider you want, it doesn't have to be a comma.
Example 8: explode() - Break a string into an array:
<?php
$num = array(5, 8, 6, 9);
#
# Example 7: Implode
#
$num_string = implode( ", ", $num); ?><br>
<?php print_r(explode(",", $num_string)); ?><br>
#
# Output:
#
Array
(
[0] => 5
[1] => 8
[2] => 6
[3] => 9
)
The explode function would divide the string back into each of the values, this is useful when working with a comma separated list, you tell it to explode based on where the commas are located.
Before I conclude this guide, in_array is an interesting array function, you can use it to check if a value exists in an array, it would return 1 for True, and empty for false, e.g:
<?php
$num = array(5, 8, 6, 9);
?>
<?php echo in_array(9, $num); # The output of this is: 1 ?><br />
<?php echo in_array(10, $num); # The output of this is: " " ?><br />