December 17th, 2008 at 12:32 pm

Unclutter array definitions in PHP

Here's a little trick how to print definitions of large arrays in a more beatiful way. Instead of passing a set of strings to the array() function, pass only one string to the explode() function!

For example, consider a section in the WordPress code (/wp-includes/post.php):

PHP:
  1. // currently
  2. $data = compact( array( 'post_author', 'post_date', 'post_date_gmt',
  3.     'post_content', 'post_content_filtered', 'post_title', 'post_excerpt',
  4.     'post_status', 'post_type', 'comment_status', 'ping_status',
  5.     'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified',
  6.     'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) );
  7.  
  8. // equals
  9. $data = compact( explode('|', 'post_author|post_date|post_date_gmt|post_content|'.
  10.     'post_content_filtered|post_title|post_excerpt|post_status|post_type|'.
  11.     'comment_status|ping_status|post_password|post_name|to_ping|pinged|'.
  12.     'post_modified|post_modified_gmt|post_parent|menu_order|guid' ) );

Not only is the second part shorter, but it is also easier to edit and to overview. Of course this always depends on how many elements your array has; it's rather ridiculous with small arrays.

Leave a Comment