Search code examples
phpfgetsstrtok

Tokenized strings to get integers from a file


i have a file.dat and its format is

1303100643 115.83
1303100644 115.94
1303100645 115.80
1303100646 115.99
1303100647 115.74
1303100648 115.11

here is the php code where i am trying to get the right integer for example in the first line i would like to get only the value "115"

while (!feof($file_handle) ) {
    set_time_limit(0);
    $line_of_text = fgets($file_handle, 1024);
    $reading=strtok($line_of_text[0]," ");
    echo $reading[0];
}

if i use reading[0] result is just "1"

On reading[1] it gives error

"SCREAM: Error suppression ignored for( ! )

Notice: Uninitialized string offset: 1 in C:\wamp\www\Delta Compression\MaxLength.php on line 16"


Solution

  • You're not using strtok() appropriately. strtok() is initialized and then each subsequent call gives you the next token. So $reading[0] is really pulling the first character of the string.

    You're using strtok() like explode(), so just use explode():

    while (!feof($file_handle) ) {
        set_time_limit(0);
        $line_of_text = fgets($file_handle, 1024);
        $reading=explode(" ", $line_of_text[0]);
        echo $reading[0];
    }
    

    i would like to get only the value "115"

    You could simply cast the result to an int or use int_val():

    echo (int)$reading[1];