0

I have an array in a file and I want to change a value from this and write it back to file like the original file.

My file with the array:

return [
    'modules' => [
        'test-module1'      => 1,
        'test-module2'      => 1,
    ],
];

I want to replace a value (the numbers) and write it back like this style to a file with PHP (when it's possible).

E.g. I want to disable test-module1 and set key to 0. What is the best way. I've no plan at this time.

EDIT: I know how to change the key but I don't know how to write it back to the file.

17
  • 3
    This seems like a poor way to format a data file. It would be better to use JSON or serialize() format. Commented Jan 25, 2017 at 20:53
  • Use var_export function Commented Jan 25, 2017 at 20:54
  • 1
    You dont want to do this. You want to have a little think about what you are doing and come up with a better way of doing it. Suggest you have a think about what @Barmar suggested Commented Jan 25, 2017 at 20:55
  • is it *.php file? Commented Jan 25, 2017 at 20:58
  • 1
    @no2br3ak Your sexual preferences are totally irrelivant here. We are an equal oportunities helper. :) Commented Jan 25, 2017 at 21:16

1 Answer 1

2

I do this with JSON. However, if you are tied to this format, it returns an array. Just include, modify and write:

$result = include('path/to/file.php');
$result['modules']['test-module1'] = 0;

But it would be difficult to get that format. You would get the other array format with var_export():

file_put_contents('path/to/file.php', 'return ' . var_export($result, true) . ';');    

Yields:

return array (
  'modules' =>
  array (
    'test-module1' => 0,
    'test-module2' => 1,
  ),
);

However, json_encode($result, JSON_PRETTY_PRINT); will yield:

{
    "modules": {
        "test-module1": 0,
        "test-module2": 1
    }
}

Then you can use file_get_contents() and json_decode() from there. No need to return.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh maybe not. The result of an include is true or false
Not when you return a value. php.net/manual/en/function.include.php Example #5
Oh yea, my testing mistake. Silly Billy Me.

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.