Search code examples
phpstring-formattingvar-dump

indentation with var_dump array output


I am auto generating some code and using var_export to output an array in a parseable format. Any ideas as to how I might get it to indent so it matches the rest of the output

protected function getCode(){
    $rs = '            $this->add(';
    $rs .= var_export($this->getArray(),true);
    $rs .= ');'.PHP_EOL;
    return $rs;
}

The output I get is like

          $this->add(array (
  'name' => 'notes',
  'attributes' => 
  array (
    'label' => 'Date',
    'label_attributes' => 
    array (
      'class' => 'col-md-4 control-label',
    ),
  ),
));

I would like it to be with correct white space

          $this->add(array (
                       'name' => 'notes',
                       'attributes' => 
                       array (
                         'label' => 'Date',
                         'label_attributes' => 
                         array (
                           'class' => 'col-md-4 control-label',
                         ),
                       ),
                     ));

Solution

  • Using preg_replace this is quite easy:

    $array = array(
        array(
            "id" => 1,
            "foo" => "bar",
        ),
        array(
            "id" => 2,
            "foo" => "baz",
        ),
    );
    
    $str = var_export($array, true);
    $str = preg_replace("/^/m", "    ", $str);
    echo "    Indent:\n";
    echo $str;