PHP: Return array from include file.

This is a short PHP guide on how to return an array from an included file. This can be particularly useful for setting up configuration files and the like.

Take a look at the following PHP file, which I have named file.php:

The file above returns an array with three elements in it.

Now, let’s say that we want to include this file and assign the array to a variable in our PHP script:

In the code snippet above, we included the file and assigned its return value to a PHP variable.

If you var_dump the $myArray variable, the result will be as follows:

As you can see, $myArray contains the array that we returned from our included file.

Note that your include file can return any kind of variable. It does not have to be an array. If you want to, your file can return an object, string or integer. This all depends on what you are trying to achieve.

Returning from an include file particularly handy if you want to return different configuration values. For example, you could include a different file depending on what database server you want to connect to:

Hopefully, these examples helped you on your way!

Facebook Comments