1

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);}

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

can I do something like that? global $config_file = file($config_file_name); inside my function?
@Radek you do not want the global keyword. It's bad practise. Just assign the modified array from the return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.