Reputation: 3044
There are 2 files on the server. A 1,495 byte large JSON file and a PHP file containing this code:
<?php
$data = json_decode(file_get_contents('data.json'), true);
for ($i = 0; $i < count($data); $i++) $data[$i][7] = '1';
?>
I get the error below. Why?
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 32 bytes) in /path/to/file/process.php on line 4
(PHP Version 5.4.45)
Upvotes: 1
Views: 328
Reputation: 4752
This sounds odd considering that your JSON file is only 1495 bytes. I'm guessing that the content of your file is in object form ({...}
) and that you're running into an infinite loop.
Consider the following program:
$json = '{"a":"0"}';
$data = json_decode ($json, true);
for ($i = 0; $i < count($data); $i++)
$data[$i][7] = '1';
Every time you run through the loop, an array element is added to the $data
object, so that count($data)
is one larger that in the previous round. The count keeps growing so the loop counter can never reach the limit.
The solution is to move the call to count
out of the loop:
$len = count($data);
for ($i = 0; $i < $len; $i++)
$data[$i][7] = '1';
Incidentally, the same problem can also happen with a JSON object in array form, with a slightly modified program:
$json = '[0]';
$data = json_decode ($json, true);
for ($i = 0; $i < count($data); $i++)
$data[$i+1][7] = '1'; // Note the +1
Upvotes: 2