1

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.

2
  • 1
    What about just using include or require instead of file_get_contents? Commented Feb 9, 2017 at 13:19
  • php.net/manual/en/function.require.php ? Commented Feb 9, 2017 at 13:19

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Is this answer enough, or you need any further assistance?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.