0

I've got this code which works well standalone:

file_put_contents('dataFile', implode('', 
    array_map(function($data) {
    return stristr($data,"NSQ = ") ? "NSQ = school\n" : $data;
    }, file('dateFile'))
));

This reads dataFile and finds the entry NSQ = and updates it to be NSQ = school

I'm going to reuse this multple times so changed it into a function:

function updatesite($site) {
file_put_contents('dataFile', implode('', 
    array_map(function($data) {
    return stristr($data,"$site = ") ? "$site = school\n" : $data;
    }, file('dateFile'))
));
}

Initially, I got an error that $site didn't exist, so I added global $site; before the return.

That stopped the error, but it doesn't update the file.

Is there any way I can use a variable like this?

1 Answer 1

5

You can use use to pass variables to a function callback like this:

function updatesite($site) {
    file_put_contents('dataFile', implode('', 
        array_map(function($data) use ($site) {
            return stristr($data,"$site = ") ? "$site = school\n" : $data;
        }, file('dateFile'))
    ));
}
Sign up to request clarification or add additional context in comments.

Comments

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.