gazrobur
gazrobur

Reputation: 139

how to convert string to Array in php with file_get_contents?

My question is, that is it possible to do, that I have a PHP file which contains an array.

$my_array = array(
   "First" => "Second",
   "Third" => "Fifth",
);

like this, and I get the content with file_get_contents

$c = file_get_contents('file.php');.


" $my_array = array(
     "First" => "Second",
     "Third" => "Fifth",
   ); "

But after this I would like to go through with a for loop

 foreach($my_array as $key => $value) {
     echo $key . ' ' . $value;
  }     

So my question is how can I unstringify or I don't know the right word for it, to get back the php array, so then I can loop through it.

Thank you for your help.

Upvotes: 1

Views: 753

Answers (1)

Jan Rydrych
Jan Rydrych

Reputation: 2258

You have to options here:

  • If the original file.php contains only the array itself and you want to use it in your script, you can use PHP's require require('file.php'); http://php.net/manual/en/function.require.php, I would prefer this option.
  • If the array definition in a string is a must, you can use PHP's eval() http://php.net/manual/en/function.eval.php, which simply executes a string as PHP code eval('$my_array = array("First" => "Second", "Third" => "Fifth");');

Then the foreach loop is gonna work

Upvotes: 2

Related Questions