Elsammak
Elsammak

Reputation: 1142

String tokenizer in php

I've a strange problem that I faced recently.
I've the following code to tokenize string in php:

$token = strtok($string, "#");

while ($token != false)
{
    echo $token;
    $token = strtok("#");

}

The simple problem I've got is that I'm parsing file which contains many numbers, so in this case 0 will be read as false. So, parsing can't be completed.

What should I do?

Upvotes: 1

Views: 2514

Answers (1)

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

You should use the !== operator, to compare $token to false :

while ($token !== false)

If you read the manual page of [**`strtok()`**][2], you'll see the following note *(quoting)* :

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "".
Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.


Using `!==` instead of `!=` will make sure there is no type-conversion done.

For instance, 0 == false ; but 0 !== false.

Upvotes: 7

Related Questions