简体   繁体   中英

How to assign values into global array inside a function? (php)

I have a function that searches for a string inside a text file. I want to use the same function to assign all lines to an array in case I am going to replace that string. So I will read the input file only once.

I have the search function working but I do not know how to deal with the array thing.

the code is something like that (I made the code sample much simpler,so please ignore the search function that actually isn't below)

function read_ini($config_file_name,$string){
 $config_file = file($config_file_name);
  foreach($config_file as $line) {
  return_string = trim(substr($line,0,15));
  $some_global_array = $line'
 }
}
echo read_ini('config.ini','database.db')
if ($replaced) {file_put_contents('config.ini', $some_global_array);}

http://php.net/parse_ini_file

I know it doesn't answer the question, but it quite possibly removes the need for even having to ask.

The deal with globals, though, is that they must be defined at the top of the function as globals, or else they're considered part of the function's scope.

function write_global() {
    global $foo;
    $foo = 'bar';
}

write_global();
echo $foo; // bar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM