Search code examples
phpstringwhile-loopmultiline

PHP while loop to read multiline text from string


I have a multiline string and that have 2 words in line. I want within a while loop while reading the script line by line get the 1st word and 2nd word.

$multilinestring="name1  5
name2 8
name3 34
name5 55 ";

The result i want to have while i am reading the the string line by line is to get 2 more strings

$firstword and $secondword

Thank you all in advance!


Solution

  • If this is really a text file you want to read, then you'd be better of to use fgets() or read the file to an array completely with file() and use explode() afterwards. Consider this code:

    $arr = file("somefile.txt"); // read the file to an array
    for ($i=0;$i<count($arr);$i++) { // loop over it
        $tmp = explode(" ", $arr[$i]); // splits the string, returns an array
        $firstword = $tmp[0];
        $secondword = $tmp[1];
    }