We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,590 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Compare in if x == z error or what?

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

2
Contributors
2
Replies
14 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
fenixZ
Light Poster
25 posts since Feb 2008
Reputation Points: 10
Solved Threads: 6
Skill Endorsements: 0

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.

diafol
Keep Smiling
Moderator
10,613 posts since Oct 2006
Reputation Points: 1,628
Solved Threads: 1,506
Skill Endorsements: 57

Thanks. This answers my question.

fenixZ
Light Poster
25 posts since Feb 2008
Reputation Points: 10
Solved Threads: 6
Skill Endorsements: 0
Question Answered as of 1 Year Ago by diafol

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.1292 seconds using 2.87MB