vishnu vishnu - 1 year ago 54
PHP Question

Remove new lines from data retrived from text file using PHP

I have following data in text file


I need to retrieve a random variable from the above text file.

I use the following php code to do that

$file = file("file.txt");
$len = count($file);
$rand = rand ( 0, $len-1 );
echo $file[$rand];

But it's returning new line along with the retrieved data. I need to retrieve data without new line.

Answer Source

Change last line to:

echo trim($file[$rand]);

trim() removes white-spaces (blanks, new lines, tabs) from the beginning and end of a string.

In order to avoid empty lines... If the last line is always the only empty one:

$rand = rand (0, $len - 2); // Instead of -1

Else, if you can have empty lines everywhere, replace the last two lines of code with:

do {
    $rand  = rand (0, $len - 1);
} while (trim($file[$rand]) == '');

echo $file[$rand];