arrays

Arrays are one of the most common types used in CMS scripts, which includes WordPress. Data is usually managed through arrays, so any functions that help us deal with them is welcomed.

PHP itself has dozens of array-focused functions, but for some operations we still need to combine them and build processes that reach our goals. Fortunately, for those developing in WordPress, it adds some other functions that can help you to attain what you need.

Array keys

I’d like to quote two particular WP-native functions to deal with array keys. They can be pretty handy in a number of situations, and are extremely easy to use. These are wp_is_numeric_array() and wp_kses_array_lc().

The first basically checks whether the keys in an array are numbered or not, returning 1 if true. The latter is more interesting – it lowercases all keys in an array, which proves to be particularly useful when we deal with external arguments, importing data to WordPress, or plugins which have unusual meta keys.

Segregating parts of an array

The function wp_array_slice_assoc() is also interesting. It slices an array for a given group of keys. So, let’s say we want to find two particular IDs in a query result. With this function, all we need to do is to provide the initial array, containing all query data, and indicate the IDs of those we want, to generate a new array.

$posts = [
  12 => array(),
  23 => array(),
  24 => array(),
  35 => array(), 
  47 => array(),
  58 => array(),
  69 => array()
]; // Entire query

$desired_posts = wp_array_slice_assoc($posts, [35, 58]);
var_dump($desired_posts);

/*
Results in

array(2) {
  [35] => array()
  [58] => array()
}
*/

Comma or space separated string as array

This is an “almost-converter” for CSV-like data into arrays. Depending on the data managed, it can be helpful, replacing some consecutive uses of PHP’s explode(). The function wp_parse_list() gets any comma separated string and converts it into an array. The good news? It works equally for space-separared strings. So:

$str1 = 'a,b,c,d,e,f';
$str2 = 'a b c d e f';

var_dump(wp_parse_list($str1));
var_dump(wp_parse_list($str2));

/*
Both result in

array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
}
*/

Cherry on top

Now, for those used to use functions like PHP’s array_walk_recursive(), WordPress offers a similar function called map_deep(). It does more than enshorten its PHP cousin. Besides the use with arrays, it can be also applied upon objects. In a simple example, let’s say we want to sanitize a serie of elements of an array.

$tosanitize = array( '
a
', 'b', '<>c
' ); $tosanitize = map_deep( $tosanitize, 'sanitize_text_field' ); /* Results in array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } */