note 43329 added to function.print-r

From: Date: Thu, 17 Jun 2004 18:15:07 +0000
Subject: note 43329 added to function.print-r
Groups: php.notes 
Request: Send a blank email to php-notes+get-71237@lists.php.net to get a copy of this message
Here's a function I use to quickly capture an array for testing in other code. It converts an array into code. <?php /** * Convert an array to code. * Recursively convert any sub arrays. */ function array_to_code($array, $nested_level=0) { $code_string = ""; // Convert each element into code. if (is_array($array)) { // Create the indent. $indent = str_repeat("\t", $nested_level); $code_string .= "array(\n"; foreach ($array as $key => $value) { // Convert this sub array to code. $element_code = array_to_code($value, $nested_level+1); // Add the new code to the string. $code_string .= $indent."\t\"".$key."\" => ".$element_code.",\n"; } $code_string .= $indent.")"; } else { // Not an array: just return with quotes. $code_string = "\"".addslashes($array)."\""; } return $code_string; } ?> Example use: <?php $test_array = array("name" => "Matt", "phone" => "1234567890", "days" => array("1"=>"Monday","2"=>"Tuesday")); print array_to_code($test_array); ?> Output: array( "name" => "Matt", "phone" => "1234567890", "days" => array( "1" => "Monday", "2" => "Tuesday", ), ) ---- Manual Page -- http://www.php.net/manual/en/function.print-r.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+43329 Delete -- http://master.php.net/manage/user-notes.php?action=delete+43329&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+43329&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#71237) next »