print an array as code

Don't know why but I could not find satisfying code anywhere.

Quickly wrote this. Let me know if you find any errors.

  function printCode($array, $path=false, $top=true) {
    $data = "";
    $delimiter = "~~|~~";
    $p = null;
    if(is_array($array)){
      foreach($array as $key => $a){
        if(!is_array($a) || empty($a)){
          if(is_array($a)){
            $data .= $path."['{$key}'] = array();".$delimiter;
          } else {
            $data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
          }
        } else {
          $data .= printCode($a, $path."['{$key}']", false);
        }    
      }
    }

    if($top){
      $return = "";
      foreach(explode($delimiter, $data) as $value){
        if(!empty($value)){
          $return .= '$array'.$value."<br>";
        }
      };
      return $return;
    }

    return $data;
  }

  //REQUEST
  $x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array()));
  echo printCode($x);

  //OUTPUT
  $array['key'] = 'value';
  $array['key2']['key3'] = 'value2';
  $array['key2']['key4'] = 'value3';
  $array['key2']['key5'] = array();

Hope this helps someone.


You're looking for var_export.


You could use var_export, serialize (with unserialize on the reserving end), or even json_encode (and use json_decode on the receiving end). The last one has the advantage of producing output that can be processed by anything that can handle JSON.

Tags:

Php

Yaml