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 :)

Link to comment
Share on other sites

<?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
*/
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.