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

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;

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);

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.