Jump to content

push data create pairs write to text file


calmchess

Recommended Posts

I pushed data into an array and now i need to take that array and break it up into pairs and the write it to text file example $vals[0] $vals[1] = pair, $vals[2] $vals[3] =pair all the way to the end of the array.....whats the best way to do this? or maybe an array push isn't the bestway in the first place please advise. 

 

$vals = array();
foreach ($_POST as $key => $value){   array_push($vals,$key,$value);    }    
$ourFileName4= "../payroll/postvals0.txt";
$ourFileHandle4= fopen($ourFileName4, 'w') or die("can't open file");
$htmlcode4=$vals[2].",".$vals[3];
fwrite($ourFileHandle4,$htmlcode4);
fclose($ourFileHandle4);

you could use a for loop to build the string you want to put into the text file

for ($i = 0; $i < count($vals); $i = $i + 2)
{
   if (isset($vals[$i + 1])) // check if there is a pair of indices (in case of odd number of data in array)
      $htmlCode4 = $vals[$i].','.$vals[$i + 1]; // create pair
   else
      $htmlCode4 = $vals[$i]; // else use the single data item (last odd one in array)
   fwrite($ourFileHandle4, $htmlCode4);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.