1

For example, I have few record of student information in few row:

AbuBaka Male
MaryLu Female
WongAhKao Male

If I want to delete the MaryLu Female record in the file, and become:

AbuBaka Male
WongAhKao Male

How to do that? if I use W or W+, all the data will be erase.

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Newbie
  • 1,584
  • 9
  • 33
  • 72

2 Answers2

1

Since there are only values, you could use file().

Example:

<?php

// Read all lines from a file to array
$users = file('users.txt',FILE_IGNORE_NEW_LINES);

// Search for the array id of the line we want to be deleted
$idToDelete = array_search('MaryLu Female',$users);

// Check if we have a result
if($idToDelete !== false){
    // If so, delete the array entry
    unset($users[$idToDelete]);
}

// Finally, put the remaining entries back into the file,
// overwriting any existing content.
file_put_contents("users.txt",implode(PHP_EOL,$users));

But be aware it's not a good idea to store data in text files. One reason is as soon as two users are using your script (given it runs on a web server) the one who saves last wins.

Database Management Systems like MySQL, MariaDB or PostgreSQL or even SQLite (which is build into php afaik) are designed to circumvent stuff you are running into when storing data in a text file.

But since I don't know your use case this was just a word of warning, maybe your use case is perfectly fine for storing names in text files. :)

3stadt
  • 171
  • 5
0

Try with this:

1.txt have inside:

AbuBaka Male
MaryLu Female
WongAhKao Male

PHP Code:

<?php

$delete = 'MaryLu Female';
$array = file('1.txt', FILE_IGNORE_NEW_LINES);

$id = array_search($delete, $array);
array_splice($array, $id, 1);
$string = implode("\n", $array);

file_put_contents('2.txt', $string);

?>

In 2.txt you will see:

AbuBaka Male
WongAhKao Male
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63