104

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?

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
bman
  • 3,740
  • 9
  • 34
  • 40
  • 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. – User Aug 16 '14 at 04: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(`echo`ed) – Gherman Mar 13 '15 at 07:17
  • For any WordPress users, this might help: https://stackoverflow.com/questions/57558027/how-to-access-an-array-variable-from-another-php-file-in-wordpress – Jesse Nickles Aug 11 '23 at 11:07

3 Answers3

187

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

Phil
  • 157,677
  • 23
  • 242
  • 245
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

Jason
  • 15,064
  • 15
  • 65
  • 105
  • 2
    When using the return value of `include`, you should be *very* careful about using parentheses around the argument. See http://php.net/manual/en/function.include.php#example-129 – Phil Aug 16 '11 at 04:53
3

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
)
Nishad Up
  • 3,457
  • 1
  • 28
  • 32