106

I have a PHP file a configuration file coming from a Yii message translation file which contains this:

<?php
 return array(
  'key' => 'value'
  'key2' => 'value'
 );
?>

I want to load this array from another file and store it in a variable

I tried to do this but it doesn't work

function fetchArray($in)
{
   include("$in");
}

$in is the filename of the PHP file

Any thoughts how to do this?

3
  • side note: if you are assigning the results of the include to a variable in the global scope make sure you use global keyword to use the variable inside a function. Commented Aug 16, 2014 at 4:03
  • 3
    Closing php-tags(?>) in files that do not contain any html and don't actually output anything are not recommended. Because any characters following after it will be output into the standard stream(echoed) Commented Mar 13, 2015 at 7:17
  • For any WordPress users, this might help: stackoverflow.com/questions/57558027/… Commented Aug 11, 2023 at 11:07

3 Answers 3

189

When an included file returns something, you may simply assign it to a variable

$myArray = include $in;

See http://php.net/manual/function.include.php#example-126

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

Comments

18

Returning values from an include file

We use this in our CMS. You are close, you just need to return the value from that function.

function fetchArray($in)
{
  if(is_file($in)) 
       return include $in;
  return false
}

See example 5# here

2 Comments

When using the return value of include, you should be very careful about using parentheses around the argument. See php.net/manual/en/function.include.php#example-129
The old anchor for Example #4 has rotted away (currently php.net/manual/en/… works). Note: whether $in goes in parentheses or not, the clearest/safest thing is to wrap the whole thing in parentheses: (include $in). Not that it matters much here though, since it's the last thing on the line.
4

As the file returning an array, you can simply assign it into a variable

Here is the example

$MyArray = include($in);
print_r($MyArray);

Output:

Array
(
    [key] => value
    [key2] => value
)

Comments

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.