Jump to content

[SOLVED] Need help removing item from array then overwriting file


John_A

Recommended Posts

I have a bookings.txt file which has a list of dates each on a new line, for example: -

 

21/06/07

22/06/07

29/06/07

25/12/07

01/01/08

 

I also have a variable $event_dd_mm_yy which I want to remove from this file if found.

 

I've managed to put the file contents into an array with: -

 

$list = explode("\n",file_get_contents("../bookings.txt"));

 

And I'm checking if the $event_dd_mm_yy is there using: -

 

if (array_search($event_dd_mm_yy, $list) === FALSE)
     {
     echo 'Date not found in file.';
     } else {
     // date found in file
     // insert code here to remove $event_dd_mm_yy from array
     // then update bookings.txt
}

 

Trouble is I don't know where to start in either removing the item from the array or re-writing the file!

 

Any help much appreciated :)

<?php
//The date to search for
$date = "22/06/07";
//The name of the file with dates in it
$file = "test.txt";

//Get the file data
$data = file_get_contents($file);
//Split file data by new line
$line = preg_split("/\n/", $data);
//Search for the date in the array
$check = array_search($date, $line);

//If the date is found
if ($check) {
echo "The date was found.";
//Remove it from the array
unset($line[$check]);
//Create the string
$new = implode("\n", $line);
//Open the file for writing, erase original data
$handle = fopen($file, 'w');
//Write the data from the new string to the file
fwrite($handle, $new);
//Close the file
fclose($handle);
}
//The date was not found, do nothing
else {
echo "The date was not found.";
}

/*
--test.txt--
21/06/07
22/06/07
29/06/07
25/12/07
01/01/08
*/
?>

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.