Well, it’s Christmas eve and I’d rather not spend too much time working on this. But this is an important chapter as arrays are incredibly useful in PHP. What makes Arrays so powerful is that they can contain any type of data, that includes strings, binary data, objects, and even more arrays (multi-dimensional). And while most other languages require array keys to be auto-incrementing numeric values starting at 0, PHP arrays are associative, meaning they let you have keys with any number or string.
Now, the stuff in this chapter is going to be quite repetitive to any normal PHP developer, so I’ll try to just cover the more interesting items.
Obviously, when creating arrays, you can define values in two ways:
- Automatic keys: array("a", "b", "c");
- Assigning keys: array(1 => "a", "candy" => "b", 923 => "c");
- Pre-Filling Data: array_fill($start, $count, $value);
Then when accessing these arrays, you can add new items in two ways:
- Automatic assignment: $arr[] = "d";
Note: this will assign a key of the largest numeric key + 1, so in the previous example "d" will have a key of 924. - Direct key access: $arr["hey"] = "d";
Interesting Tidbits:
- Keys are case-sensitive but type-insensitive, meaning $arr['c'] != $arr['C'] but $arr['5'] == $arr[5].
- Arrays can be "unraveled" by using the list function. This will associate the array values into variables.
-
echo $name; // Displays: Billy Bob
- Using the plus sign (+) can add arrays together. Common keys are not duplicated.
-
$b = array("s", 5 => "t", 9 => "j");
-
$c = $a + $b;
-
// $c is equal to (0 => "x", 1 => "y", 2 => "z", 5 => "t", 9 => "j");
-
// "s" is not included because it's key was 0 which was already in the first array.
- Comparing arrays follows this format: == operator returns true if the arrays have the same values and keys regardless of order. === operator returns true if the arrays have the same values/keys and in the same order.
- Use count($array) to determine the array length and is_array($array) to test if it is an array (duh).
- Personal Note: do not use count($array) in a for loop for two reasons: one, PHP executes that function every loop iteration causing a waste of CPU time and two, if you remove array values, the length of the loop will decrease and not allow you to reach the true end of the array. Example:
-
for ($i = 0; $i < count($array); $i++) {
-
echo $array[$i];
-
unset($array[$i]);
-
}
-
// Outputs: 1, 2, 3 instead of 1, 2, 3, 4, 5
- As you can see from above, you can delete an item in an array by using the unset() function.
- Two useful functions for checking whether an item exists in an array are by key, array_key_exists($key, $array) and by value, in_array($value, $array);
- In the event you want to "flip" an array’s values with its keys, you can use the array_flip($array) function.
- And to reverse the order of an array, use the array_reverse($array) function.
I’m going to have to call it quits here as there are presents down the hall, calling my name!!

