Search code examples
phpfgetc

How to know if the line is empty while reading char by char in PHP


How do I differentiate between an empty line and an endofline in PHP while reading character by character. In short I want to know how to find an empty line while reading char by char. Let me know if anything is unclear with a comment. Thank you...


Solution

  • You can either collect the characters of the current line in a buffer and then count when you see the end of line.

    $buffer = '';
    while (($char = fgetc($fp)) !== false) {
        if ($char != '\n') {
            $buffer .= $char;
        } else {
            if (strlen($buffer) == 0) {
                echo "Empty line\n";
            } else {
                echo "Non-empty line\n";
            }
    
            $buffer = '';
        }
    }
    

    Or you keep a count of characters while you read, until you see the end of line

    $count = 0;
    while (($char = fgetc($fp)) !== false) {
        if ($char != '\n') {
            ++$count;
        } else {
            if ($count == 0) {
                echo "Empty line\n";
            } else {
                echo "Non-empty line\n";
            }
    
            $count = 0;
        }
    }
    

    As you can see, both versions are similar, it only depends on whether you need the line afterwards or not.


    To consider \r, you can compensate when you see one immediately before a \n, e.g.

    $cr = false;
    $count = 0;
    while (($char = fgetc($fp)) !== false) {
        if ($char != '\n') {
            $cr = false;
            ++$count;
            if ($char == "\r")
                $cr = true;
        } else {
            if ($cr)
                --$count;
    
            if ($count == 0) {
                echo "Empty line\n";
            } else {
                echo "Non-empty line\n";
            }
    
            $count = 0;
        }
    }
    

    $cr is true, if the previous character was a \r. So if you look at a newline and $cr is true, you have a CRLF and decrement the character count by one.

    As an alternative, you can collect the whole line and trim whitespace before looking at the length

    if (strlen(trim($buffer)) == 0) {
        echo "Empty line\n";
    } else {
        echo "Non-empty line\n";
    }
    

    Even though not asked, reading a whole line and checking might be more efficient, e.g.

    while (($buffer = fgets($fp)) !== false) {
        if (strlen(rtrim($buffer, "\n")) == 0) {
            echo "Empty line\n";
        } else {
            echo "Non-empty line\n";
        }
    }