Arrays in PHP, Continued
In continuing to learn about arrays and data structures in PHP, I’ve been playing around with a few cool functions.
array_column();
is a handy method in PHP5.5 that returns all of the values of a single column, given the key.
Let’s say I had the following associated array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
If I wanted all of the cat’s names, I would write:
1
|
|
array_key_exists();
is a function that checks if an array contains a given key, returning true or false.
From $catCelebs
above, if I wanted to check if age was an included column, I would write:
1 2 3 |
|
Similar to this are two other useful functions that allow you to search arrays: in_array();
searches an array for a value and returns true or false if it exists, and array_search();
looks for a value and returns its key if it exists, and false otherwise.
array_unique();
, much like the name suggests, will remove duplicates from a given array, the return of that being a new array. This function does not change the original array, so reassignment would be necessary.