Arrays are very common in PHP and if you do any type of coding in WordPress you’re likely to encounter them. In this article I explain the basics of what an array is and how to work with them.
Arrays
An array is actually an ordered map. A map is a type that associates values to keys.
PHP Manual
An array can be created using the array() language construct. It takes any number of comma-separated key => value
pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Array Functions
You can find all array() functions in the PHP Manual, https://www.php.net/manual/en/ref.array.php. The functions you’ll likely use most often are:
array_diff() :: Compares an array against other arrays and returns the values that are not present in any of the others.
array_intersect() :: Compares an array against other arrays and returns the values that are present in all of them.
array_key_exists() :: Checks if a given key or index exists
array_merge() :: Merges the elements of one or more arrays
array_push() :: Push elements onto the end of an array
array_replace_recursive() :: Replaces elements from passed arrays into the first array recursively
array_reverse() :: Return an array with elements in reverse order
array_slice() :: Extract a slice of an array
array_unique() :: Removes duplicates from an array
array_unshift() :: Prepend elements to the beginning of an array
count() :: Counts all elements in an array
in_array() :: Checks if a value exists in an array
Array Functions with callbacks
array_filter() :: Filters elements of an array using a callback function. If no callback is supplied, all empty entries of arrays will be removed.
array_map() :: Applies the callback to the elements of the given arrays
array_udiff() :: Computes the difference of arrays by using a callback function for data comparison
Coding Examples
Recently Viewed Widget
I implemented my own version of “recently viewed” using the existing Woo widget data. In this code I use:
- array_map() to cast all values as integers
- array_filter() to remove empty elements
- array_reverse() to show the element added last at beginning
$viewed_products =
! empty( $_COOKIE['woocommerce_recently_viewed'] )
? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) )
: array();
$viewed_products =
array_reverse(
array_filter(
array_map( 'absint', $viewed_products ) ) );
Merging arrays in a filter
This is a very common example. For WP filters containing arrays as return, you’d use array_merge to merge the original array and your own new array. In this example I needed to register new search query vars in a class object:
public function add_query_vars( $vars ) {
return array_merge(
$this->new_vars,
$vars
);
}
add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
Insert a value after a specific key
This is a useful function I found on github to insert a value after a specific key in an array. It uses:
- array_slice to slice the existing array at the point of insertion
- arrray_merge to recombine the elements
/**
* Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended
* to the end of the array.
*
* @param array $array
* @param string $key
* @param array $new
*
* @return array
* Source https://gist.github.com/wpscholar/0deadce1bbfa4adb4e4c
*/
function array_insert_after( array $array, $key, array $new, $strict = true ) {
$keys = array_keys( $array );
$index = array_search( $key, $keys, $strict);
$pos = false === $index ? count( $array ) : $index + 1;
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) );
}
WordPress Functions
WordPress Array Functions
WP also has its own functions to handle arrays. Below is a non-exhaustive list from the WP Code Reference:
_wp_array_get() :: Accesses an array in depth based on path of keys
_wp_array_set() :: Sets an array in depth based on a path of keys
wp_kses_array_lc() :: Converts the keys of an array to lowercase
wp_is_numeric_array() :: Determines if it is a numeric-indexed array
wp_array_slice_assoc() :: Extract a slice, given a list of keys
__return_empty_array() :: returns an empty array. Useful for filters.
WordPress Array + Object Functions
WP also offers functions which work for both arrays and objects. Below is a non-exhaustive list of functions I use regularly:
wp_list_pluck() :: Plucks a certain field out of each object or array in an array.
Coding Examples
Flatten an ACF repeater field array
This is a quick way to extract an array from an ACF repeater field, for example, to use in a select dropdown:
$multi_array = get_field( 'repeater_field' );
$array = wp_list_pluck( $multi_array, 'sub_field' );
Changes:
Array (
[0] => Array ( [sub_field] => lorem ipsum )
[1] => Array ( [sub_field] => dolor sit )
)
Into:
Array (
[0] => lorem ipsum
[1] => dolor sit
)
Interested in PHP? Got a great array function or a query? Let me know in the comments below!
Leave a Reply