1,105,409 Community Members

Compare in if x == z error or what?

Member Avatar
fenixZ
Light Poster
25 posts since Feb 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi guys,
I am experienced in PHP or at least until today I was thinking so.
I am not sure what is it all about exactly. In my opinion the following code should not echo anything BUT IT DOES.

$cache = 'all';
	if($cache == 0)
	{
		echo 'Execute something';
	}

If I do the same but compare with 1,2,3,4.. or any other (int), comparison returns FALSE. Only when 0 (int) compared with string gives TRUE.
WHY? It definitely has something to do with type conversion but I can not figure it out.
When I compare with === (no type conversion) it seems to work as expected, but this does not answer my question.

Please throw a little more light on the subject.

Here is the reference

Member Avatar
diafol
Where are my eyes?
12,977 posts since Oct 2006
Reputation Points: 1,821 [?]
Q&As Helped to Solve: 1,848 [?]
Skill Endorsements: 92 [?]
Moderator
Featured
Sponsor
 
1
 

AFAIK, number string comparisons automatically change the string to a number. If the string does not include a number in a recognizable format, it is given the value of 0.

That's my take, I may be wrong. That's why I always test with ===false and not ==0 or similar as you may get weird positive matches.

Member Avatar
fenixZ
Light Poster
25 posts since Feb 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks. This answers my question.

Question Answered as of 2 Years Ago by diafol
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: