Skip to main content

Arrays and Data Shaping

Indexed and Associative Arrays

$items = ['apple', 'banana', 'orange'];
echo $items[0];
$args = [
'post_type' => 'post',
'posts_per_page' => 10,
'post_status' => 'publish',
];

WordPress APIs heavily use associative arrays for arguments.

Add and Read Values

$items[] = 'pear';
$settings['enabled'] = true;
$limit = isset($settings['limit']) ? absint($settings['limit']) : 10;

Merge and Defaults

$args = array_merge($defaults, $overrides);

In WordPress, use wp_parse_args() for argument defaults.

$args = wp_parse_args($args, [
'limit' => 10,
'order' => 'DESC',
]);

Map, Filter, Reduce

$ids = array_map('absint', $raw_ids);
$published = array_filter($posts, function ($post): bool {
return 'publish' === $post->post_status;
});
$total = array_reduce($prices, function (float $carry, float $price): float {
return $carry + $price;
}, 0.0);

Keys, Values, and Columns

$keys = array_keys($settings);
$values = array_values($settings);
$ids = array_column($rows, 'ID');

Strict in_array

if (in_array($layout, ['grid', 'list'], true)) {
$safe_layout = $layout;
}

Sorting

FunctionPreserves KeysSorts By
sort()NoValues ascending
rsort()NoValues descending
asort()YesValues ascending
arsort()YesValues descending
ksort()YesKeys ascending
krsort()YesKeys descending
usort()NoCustom comparison
uasort()YesCustom comparison
usort($items, function (array $a, array $b): int {
return $a['priority'] <=> $b['priority'];
});

Destructuring and Spread

[$first, $second] = $items;
['title' => $title, 'url' => $url] = $card;
$combined = [...$default_items, ...$custom_items];

Array spread requires PHP 7.4+.

WordPress Query Arrays

$query = new WP_Query([
'post_type' => 'book',
'posts_per_page' => 12,
'tax_query' => [
[
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => ['fiction'],
],
],
]);

Sanitizing Arrays

$raw_ids = isset($_POST['ids']) ? (array) wp_unslash($_POST['ids']) : [];
$ids = array_map('absint', $raw_ids);
$ids = array_filter($ids);

Shape Validation

function myplugin_is_valid_card(array $card): bool {
return isset($card['title'], $card['url'])
&& is_string($card['title'])
&& is_string($card['url']);
}

Practical WordPress Pattern

function myplugin_get_settings(): array {
$settings = get_option('myplugin_settings', []);

if (! is_array($settings)) {
$settings = [];
}

return wp_parse_args($settings, [
'enabled' => false,
'limit' => 10,
'layout' => 'grid',
]);
}

Common Pitfalls

  • Assuming request arrays are shaped correctly.
  • Forgetting wp_unslash() for superglobal arrays.
  • Using array_merge() when numeric keys matter.
  • Using in_array() without strict mode.
  • Storing huge arrays in autoloaded options.
  • Creating deeply nested arrays with no documented schema.