I have a little script that use the function file() for reading the entire file into an array.
$arr = file('file.txt');
The file.txt is structured like this:
john
david
james
So if I debug the array it returns:
array(4) {
[0]=>
string(6) "john
"
[1]=>
string(7) "david
"
[2]=>
string(2) "
"
[3]=>
&string(5) "james"
}
I'm trying to find a way to detect the empty line when I analyze every value of the array in a foreach loop:
foreach ($arr as $value) {
I tried with the empty function but nothing.. I also tried with comparing the value with PHP_EOL
or , also nothing.
I know that I can avoid empty lines with FILE_IGNORE_NEW_LINES, but I don't need it. I'm just searching for a way to detect this empty lines.
You should not use file
directly, it may result in memory problems. In stead try this.
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
// Trim will remove any whitespace prepended/appended
// Empty line will now result in empty string
$line = trim(fgets($file));
}
fclose($file);
you can trim()
$value befor you test it with empty()
like this :
if(empty(trim($value)) {
// $value is empty
}
if it's not working test it with preg_match()
like this:
foreach ($arr as $value) {
if(preg_match("/(^[
]*|[
]+)[\s\t]*[
]+/", $value)) {
// $value is empty
}
}
Use trim()
and continue
:
$arr = file('file.txt');
foreach ($arr as $value) {
if ('' === trim($value)) {
// line is empty
continue;
}
// process non-empty line here
}
For reference, see: