mrpatg
mrpatg

Reputation: 10117

invalid argument when imploding in php

Im getting invalid argument error when running the following code. Im trying to change the value of a line in the $info array, then implode it, implode its parent array, and then save the whole shebang back to whence it came.

$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
    foreach ( $csvpre AS $key => $value){
        $i++;
        if($i = $row){
            $info = explode("%%", $value);
            $info[$target] = $newfieldvalue;

            $presave = implode("%%", $info);    
        }           
    }


$save = implode("###", $presave);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);

update below

$rowpre = $_GET['row'];
$newfieldvalue = $_GET['nfv'];
$target = $_GET['target'];
$row = --$rowpre;
$data = file_get_contents("temp.php");
$csvpre = explode("###", $data);
$i = 0;
    foreach ( $csvpre AS $key => $value){
        $i++;
        if($i == $row){
            $info = explode("%%", $value);
            $info[$target] = $newfieldvalue;

            $csvpre[$key] = implode("%%", $info);  
        }           
    }


$save = implode("###", $csvpre);
$fh = fopen("temp.php", 'w') or die("can't open file");
fwrite($fh, $save);
fclose($fh);

Target is the field within the selected Row that i wish to update with the newfieldvalue data.

Upvotes: 0

Views: 291

Answers (2)

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41316

$presave contains the last processed line (i.e. a string) and implode expects an array. To store the line back in the original array, change:

$presave = implode("%%", $info); 

to:

$csvpre[$key] = implode("%%", $info); 

And to convert the whole CSV array into a string, change:

$save = implode("###", $presave);

to:

$save = implode("###", $csvpre);

And one more problem:

if($i = $row){

should be:

if($i == $row){

because you want to compare the variables, not assign $i.

Upvotes: 1

ty812
ty812

Reputation: 3323

$save = implode("###", $presave);

At that point, $presave is a string, and should be an array to work with implode. Create an array where you push the $presave-values, and implode that one.

Upvotes: 2

Related Questions