jonlink
jonlink

Reputation: 531

Cast as int or leave as string?

I'm wondering if there is any reason to cast my variable, which is returned from MySQL as a string, as an int. I'm updating some code and netbeans wants me to use === instead of ==. The problem is that === cares as much about the content as it does the type.

I had: if($user['user_state']==1){...}

So I change it to this: if($user['user_state']==="1"){...}

or I can do this: if((int)$user['user_state']===1){...}

It doesn't make a difference to me if I've got an int or str. I certainly won't be doing any math with this particular variable. And since I'll have to rewrite my conditionals in any case, I'd rather do it the right way.

So, I think my question is what is best practice? Or is this one of those wonderful questions whose answers will end happy marriages like single vs double quotes?

Upvotes: 6

Views: 131

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

The underlying reason for Netbeans to suggest such a thing is likely this:

"1abc" == 1 // true

Strengthening the comparison by applying an (int) cast and using === will satisfy the editor and purists, but since you would typically trust your database schema, the above cast won't be necessary and you can use a loose comparison instead.

To sum it up, although strict comparisons are a good practice in general it's often considered overzealous when working with external data such as databases and (to a lesser extent) posted data.

That said, it still leaves the matter of making Netbeans ignore these "issues" in a sensible way; having special instructions littered in your code is not a great situation either.

Upvotes: 4

Related Questions