Search code examples
phparraysfile-put-contents

How add php array with file_put_contents ? - PHP


i want to add/create a php file with inside an array using file_put_contents().

$arr= array('red');
$content= "<?php \n$".$var."=".$arr."\n?>"; 
file_put_contents('file.php', $content);    

But then if i open file.php i read this:

 <?php
 $var=Array
 ?>

i would to see array('red')

I tried also serialize() but the output is bad...


Solution

  • Converting an array to a string just returns Array. You can use var_export() to get an array literal to use there.

    $content = "<?php \n\$" . $var . "=" . var_export($arr, true) . "\n?>";