Manipulating an Array
Adding element to start of array
Sometimes you want to add an element to the beginning of an array without modifying any of the current elements (order) within the array. Whenever this is the case, you can use
array_unshift()prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
Taken from the PHP documentation for
If you'd like to achieve this, all you need to do is the following:
This will now add
4 as the first element in your array. You can verify this by:
This returns an array in the following order:
4, 1, 2, 3.
array_unshift forces the array to reset the key-value pairs as the new element let the following entries have the keys
n+1 it is smarter to create a new array and append the existing array to the newly created array.
Exchange values with keys
array_flip function will exchange all keys with its elements.
Filtering an array
In order to filter out values from an array and obtain a new array containing all the values that satisfy the filter condition, you can use the
Filtering non-empty values
The simplest case of filtering is to remove all "empty" values:
Filtering by callback
This time we define our own filtering rule. Suppose we want to get only even numbers:
array_filter function receives the array to be filtered as its first argument, and a callback defining the filter predicate as its second.
Filtering by index
A third parameter can be provided to the
array_filter function, which allows to tweak which values are passed to the callback. This parameter can be set to either
ARRAY_FILTER_USE_BOTH, which will result in the callback receiving the key instead of the value for each element in the array, or both value and key as its arguments. For example, if you want to deal with indexes istead of values:
Indexes in filtered array
array_filter preserves the original array keys. A common mistake would be to try an use
for loop over the filtered array:
This happens because the values which were on positions 1 (there was
0), 3 (
null), 5 (empty string
'') and 7 (empty array
) were removed along with their corresponding index keys.
If you need to loop through the result of a filter on an indexed array, you should first call
array_values on the result of
array_filter in order to create a new array with the correct indexes:
Merge two arrays into one array
- Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
- If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
- Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
Removing elements from an array
To remove an element inside an array, e.g. the element with the index 1.
This will remove the apples from the list, but notice that
unset does not change the indexes of the remaining elements. So
$fruit now contains the indexes
For associative array you can remove like this:
Now $fruit is
unsets the variable and thus removes the whole array, meaning none of its elements are accessible anymore.
Removing terminal elements
array_shift() - Shift an element off the beginning of array.
array_pop() - Pop the element off the end of array.
Sorting an Array
There are several sort functions for arrays in php:
Sort an array in ascending order by value.
Sort an array in descending order by value.
Sort an array in ascending order by value and preserve the indecies.
Sort an array in descending order by value and preserve the indecies.
Sort an array in ascending order by key
Sort an array in descending order by key.
Sort an array in a way a human being would do (natural order).
Sort an array in a way a human being would do (natural order), but case intensive
Shuffles an array (sorted randomly).
As written in the description it is random so here only one example in what it can result
Sort an array with a user defined comparison function.
Sort an array with a user defined comparison function and preserve the keys.
Sort an array by keys with a user defined comparison function.
Whitelist only some array keys
When you want to allow only certain keys in your arrays, especially when the array comes from request parameters, you can use
array_intersect_key together with
parameters variable doesn't contain any allowed key, then the
filteredParameters variable will consist of an empty array.
array_filter gives the additional flexibility of performing an arbitrary test against the key, e.g.
$allowedKeys could contain regex patterns instead of plain strings. It also more explicitly states the intention of the code than
array_intersect_key() combined with