Menu

Add Values to an Associative Array with array_push() in PHP
📰

Add Values to an Associative Array with array_push() in PHP

DEV Community: php·Kevinleary.net·12 days ago
#4IVqoJ7r
#devto#dev#work#array#query_args
Reading 0:00
15s threshold
Cover image for Add Values to an Associative Array with array_push() in PHP

Kevinleary.net

This snippet will add values to an associative array. Normally I use array_push() for this, but that function doesn’t work with associative arrays in PHP.

Source code

$array[$key] = $value;

Enter fullscreen mode Exit fullscreen mode

Working example

/** Array to store WordPress WP_Query arguments */
$query_args = array('posts_per_page' => '-1');

/** Get the post type for the current post */
$queried_post_type = get_query_var('post_type');

/** Define WP_Query arguments based on the section of the site */
if ( is_single() && $queried_post_type == 'our-work' ) {
    $query_args['post_type'] = 'our-work';// Query "Our work" posts for the sidebar if an "Our work" post is being viewed
} else {
    $query_args['post_type'] = 'page'; // Query pages for the sidebar if a page is being viewed
}

/** Start the query */
$query = new WP_Query($query_args);

Enter fullscreen mode Exit fullscreen mode