1

I'd like to know how to check if a text file is empty or not. It means that there is no text even some space, i.e. it was blank

function keyRemain($path)
{
    $ambil = file_get_contents("data/$path/keywords.txt");
    $kw = explode(",", $ambil);
    if (count($kw) > 1) {
        return false;
    } else {
        return true;
    }
}
SaidbakR
  • 13,303
  • 20
  • 101
  • 195
Rafi Halilintar
  • 79
  • 1
  • 10

3 Answers3

4

You have to check the empty function along with trim

function keyRemain($path)
{
    $ambil = trim(file_get_contents("data/$path/keywords.txt"));
    var_dump($ambil); // check the output here
    if(!empty($ambil)) {
        return false;
    } else {
        return true;
    }
}
pravindot17
  • 1,199
  • 1
  • 15
  • 32
1

Maybe this was not the answer, just the another way to check the file. Before this was happend, the code appear instead the class. After i cut it and move it outside of the class it work perfectly without any errors.

Rafi Halilintar
  • 79
  • 1
  • 10
-1

file_get_contents() will read the whole file while filesize() uses stat() to detirmine the file size. Use filesize(), it should consume less disk I/O.

That's the answer found here, on stack...

You can also (on same link there's this answer):

clearstatcache();
if(filesize($path_to_your_file)) {
    // your file is not empty
}
Marcelo Agimóvel
  • 1,668
  • 2
  • 20
  • 25