Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load return array from a PHP file?

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?

like image 208
bman Avatar asked Aug 16 '11 04:08

bman


People also ask

How do I get an array from a file?

Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.

Can you return an array in PHP?

In PHP you can return one and only one value from your user functions, but you are able to make that single value an array, thereby allowing you to return many values.

How do I return a PHP file?

If return is used outside of a function, it stops PHP code in the file from running. If the file was included using include , include_once , require or require_once , the result of the expression is used as the return value of the include statements.

What does @file mean PHP?

A file with the . php file extension is a plain-text file that contains the source code written in the PHP (it's a recursive acronym meaning PHP: Hypertext Preprocessor) programming language. PHP is often used to develop web applications that are processed by a PHP engine on the web server.


2 Answers

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

like image 105
Phil Avatar answered Oct 04 '22 21:10

Phil


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

like image 39
Jason Avatar answered Oct 04 '22 22:10

Jason