'Get array from the same file, multiple times

I'm trying to get an array value from array.app.php. I'm doing this using a function, but when I use include_once, it'll eventually return 1. When I use include, it'll exhaust my memory. It seems like i'm not doing it effeciently enough.

Content of array.app.php

return [
   'name' => 'Example app'
];

Function that returns: 1

function getArray($file, $key): string
{
   $array = include_once "{$name}.php";
   return $array[$key];
}

Function that exhausts memory

function getArray($file, $key): string
{
   $array = include "{$name}.php";
   return $array[$key];
}

The main idea is that I want to be able to call this function multiple times so that it returns the key value I need. If I call one of those functions once, it'll work fine.

I know that the file contents of array.app.php could be different, like JSON, but that's not what I'm trying to achieve, it's really just my goal to make this work.



Solution 1:[1]

As you sad, with include_once you getting true, because:

if the code from a file has already been included, it will not be included again, and include_once returns true. https://www.php.net/manual/en/function.include-once.php

So you need to use include. Maybe you can clear variables from memory using unset() or $var = null. You can read about the difference here - What's better at freeing memory with PHP: unset() or $var = null

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MTpH9