A print_r() or var_dump() replacement that expands the variable into valid PHP code.

Occasionally you want to expand an object or array variable to see what it contains. Typically we would use a variation of print_r() or var_dump() to do this, but the down side is there is no way simple way to grab the outputted array or object data and put it back in your code. This function helps with that issue.

/**
 * A `print_r` or `var_dump` replacement that expands the variable into valid PHP code.
 * @uses   var_export
 * @param  array|object  $array_or_object $variable to expand/view
 * @param  boolean       $echo            Whether to return or display the data
 * @return string                         Variable representation that is valid PHP code.
 */
function expand_code( $array_or_object, $echo = true ) {
  // This is the real magic
  $expanded = var_export( $array_or_object, true );
  // This makes object representations more reliable
  $expanded = str_ireplace( 'stdClass::__set_state', '(object) ', $expanded );
  // Assign output to a variable
  $expanded = '<xmp>$expanded = '. $expanded .'</xmp>';

  if ( $echo ) echo $expanded;

  return $expanded;
}

The Gist

Comment

Fast, secure WordPress hosting is provided by WP Engine.
%d bloggers like this: