Search code examples
phparraysincludefwrite

Search And Replace Existing Array Element Within File - PHP


$static = ');';
$file = 'onebigarray.php';
$fh = fopen($file, 'r+');
include $file;
if (in_array($keyname, $udatarray)) {
    $key = array_search($keyname, $udatarray);
    $fsearch = $key + 4;
    fseek($fh, $fsearch, SEEK_END);
    fwrite($fh, 'new data');
    fseek($fh, - 2, SEEK_END);
    fwrite($fh, $static);
    fclose($fh);
}

I'm a novice at PHP. What I've done is created a form that writes array elements to a file "onebigarray.php". The file looks like

Array (
'name',
'data',
'name2',
'data2',
);

What I ultimately need to do, is load that $file, search the array for an existing name then replace 'data(2)' with whatever was put in the form. The entire script is extremely large and consists of 3 different files, it works but now I need to find a way to search and replace array elements within an existing file, and then write them to that file. This section of the script is where that's going to need to occur and it's the part that's giving me the most trouble, currently it seems to properly load and enact the if/else statement, however completely ignores fwrite (I can only assume there's an issue with including and opening the same file within the same script).

Thank you in advance for any help.


Solution

  • Your code can be simplified greatly, but with some notable design changes. Firstly, your stored array structure is not efficient and negates the benefit of using an array in the first place. A very powerful feature of arrays is their ability to store data with a meaningful key (known as an associative array). In this case your array should look like this:

    array(
        'name' => 'data',
        'name2' => 'data2'
    );
    

    This allows you to retrieve the data directly by the key name, e.g. $data = $array['name2'].

    Secondly, changing the data stored in 'onebigarray.php' from PHP code to JSON makes it trivial for any other system to interact and makes it easier to extend later.

    Assuming that the file is renamed to 'onebigarray.json' and its content looks like this (after using json_encode() on the array above):

    {"name":"data","name2":"data2"}
    

    Then the below code will work nicely:

    <?php
    $file = 'onebigarray.json';
    $key = 'name2';
    $new_data = 'CHANGED';
    
    $a = (array) json_decode(file_get_contents($file));
    
    if (array_key_exists($key, $a)) {
        $a[$key] = $new_data;
    
        file_put_contents($file, json_encode($a));
    }
    ?>
    

    After running the above, the JSON file will now contain this:

    {"name":"data","name2":"CHANGED"}
    

    A big caveat: this will read the entire JSON file into memory! So depending on how big the file really is this may negatively impact server performance (although it would probably need to be several megabytes before the server even noticed, and even then with a trivial impact on performance).