1

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.

Mastraio
  • 15
  • 4
  • Hey, use JSON, you have to serialize your data, using `json_encode()` and `json_decode()`, then yes you can store a lot of data in files, for training, PHP handle json files of many GB without problems very fast, locally of course. Don't store user data, or any data, in .php files, use non executable files, like JSON, or .csv, or of course a proper SQL database! – NVRM Apr 02 '22 at 14:28

1 Answers1

0

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

MTpH9
  • 304
  • 2
  • 10