vendredi 27 septembre 2019

Strange behavior of PHP value comparison [duplicate]

This question already has an answer here:

I see there are similar questions but they are normally related to integer numbers being compared.

In this case I stumbled upon the following situation.

I have a category id that's taken from a Firebase database and it's a generated ID that looks like this:

-Kk9O6BWamcuUWzkemIr1

Now my thoughts were, well it's obvious it's a string, but as PHP is not very strict with formats I decided to do the following.

if($category_id != 0) { ... }

To explain a little, my default value for when there's no category is 0, so this would be the exception when category_id is not equal to 0.

Then what happened is that when the condition became if('-Kk9O6BWamcuUWzkemIr1' != 0) the script interpreted it as false and never did what was inside of it.

What I did was change the if to if($category_id) but I fear that's a little too broad.

My theory is that if I don't specifically cast -Kk9O6BWamcuUWzkemIr1 as a string, PHP interprets it as a negative number because of the starting - sign. I am not sure if that's what's happening or it's some other thing.

What would be the correct comparison in this case?

Aucun commentaire:

Enregistrer un commentaire