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:

<?php

/**
 * Example PHP array that we will be returning
 */

return array(
    'dog', 'cat', 'horse'
);

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:

<?php

//Include file.php and assign it to a variable
$myArray = include 'file.php';

//var_dump it
var_dump($myArray);

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:

$databaseDetails = false;

//If it's a production server.
if(PRODUCTION){
    //Include production.php
    $databaseDetails = include 'production.php';
} else{
    //Otherwise, include the development.php database details.
    $databaseDetails = include 'development.php';
}

//Connect to DB using $databaseDetails.

Hopefully, these examples helped you on your way!