I am just now training PHP.
About the following code,I read a schedule from file,and overwrite or delete if there is given line number($lineNo) in file.
Then I have a question.
Is when a file pointer is updated when fwrite function have carried out?
<?php
$filename = "sample.txt";
function edit($filename,$lineNo){
$new_line = "Hello";
$schedule_list = file($filename);
$fp = fopen($filename,"w");
foreach($schedule_list as $schedule_lineNo => $line){
if($schedule_lineNo == $lineNo){
if($_POST["mode"] == "overwrite"){
fwrite($fp,$new_line);
}
elseif($_POST["mode"] == "delete"){
}
else{
fwrite($fp,$line);
}
}
fclose($fp);
}
?>
Don't over complicate things. Since you using file() function, and your feeding the line number desired, use that line number to designate which array key you will overwrite. Example:
$filename = "sample.txt";
function edit($filename, $lineNo){
$new_line = "Hello";
$schedule_list = file($filename, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
if(!isset($schedule_list[$lineNo-1])) {
return false;
}
if(/** overwrite **/) {
// use the line number as key and use it on the array returned by file()
$schedule_list[$lineNo - 1] = $new_line; // numeric indices start at zero
} elseif(/** delete **/) {
unset($schedule_list[$lineNo-1]);
}
file_put_contents($filename, implode("\n", $schedule_list));
return true;
}
var_dump(edit($filename, 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With