Posted By

BrunoDeBarros on 12/10/10


Tagged

php array print output export


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrunoDeBarros


Output/Print an array as PHP code.


 / Published in: PHP
 

URL: http://terraduo.com

Prints an array (recursive) as PHP code (can be pasted into a php file and it will work).

Note: This function can process arrays with integers/strings/sub-arrays. It is impossible to process resources (they have a state), and while it is possible to process objects, I didn't see a need for it. However, if you need it to support objects as well, I'll be more than happy to alter the function. Just drop a comment to let me know.

  1. /**
  2.  * Print an array (recursive) as PHP code (can be pasted into a php file and it will work).
  3.  * @param array $array
  4.  * @param boolean $return (whether to return or print the output)
  5.  * @return string|boolean (string if $return is true, true otherwise)
  6.  */
  7. function printArrayAsPhpCode($array, $return = false) {
  8. if (count($array) == 0) {
  9. if (!$return) {
  10. print "array()";
  11. return true;
  12. } else {
  13. return "array()";
  14. }
  15. }
  16. $string = "array(";
  17. if (array_values($array) === $array) {
  18. $no_keys = true;
  19. foreach ($array as $value) {
  20. if (is_int($value)) {
  21. $string .= "$value, ";
  22. } elseif (is_array($value)) {
  23. $string .= printArrayInPHPFormat($value, true) . ",\n";
  24. } elseif (is_string($value)) {
  25. $string .= "$value', ";
  26. } else {
  27. trigger_error("Unsupported type of \$value, in index $key.");
  28. }
  29. }
  30. } else {
  31. $string .="\n";
  32. foreach ($array as $key => $value) {
  33. $no_keys = false;
  34. if (is_int($value)) {
  35. $string .= "\"$key\" => $value,\n";
  36. } elseif (is_array($value)) {
  37. $string .= "\"$key\" => " . printArrayInPHPFormat($value, true) . ",\n";
  38. } elseif (is_string($value)) {
  39. $string .= "\"$key\" => '$value',\n";
  40. } else {
  41. trigger_error("Unsupported type of \$value, in index $key.");
  42. }
  43. }
  44. }
  45. $string = substr($string, 0, strlen($string) - 2); # Remove last comma.
  46. if (!$no_keys) {
  47. $string .= "\n";
  48. }
  49. $string .= ")";
  50. if (!$return) {
  51. print $string;
  52. return true;
  53. } else {
  54. return $string;
  55. }
  56. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: BrunoDeBarros on January 7, 2011

Dear god, I was so stupid to make this.

Use var_export($array); to do this.

You need to login to post a comment.