Click to See Complete Forum and Search --> : Difference between ($a==$b) and ((string)$a===(string)$b)


bigBA
January 7th, 2005, 11:04 AM
we have some functions at work to connect and query our backend.
so i searched a little bit in its sourcecodes (i wanted to duplicate a function and modify it a bit) and i discovered one thing, that i do not fully understand or rather i think that they are equivalent.. but i think there must be some kind of cause for this.

the function i mentioned creates an option list out of two arrays (one for the values and one for the displayed texts).
and in addition a value, which should be marked as <selected>.

there are two ways the function will work, either you supply two arrays or just one. in the last case, the value and text informations are taken from the key and the value of the array.

so in the first case comparison of the selected value is done in this way:

if( ((string)$value[$i]===(string)$selected) )
//......

in the second case, comparison is done like this:

if( $key == $selected )
//....


as i understand "==" compares just the values, not the type so 1 as string should match against 1 as an integer. well.. it does :)

and "===" compares value and type. so that 1 as string would not match against 1 as integer.
but... as you see in the code listing above the two values are casted to string before the "===" operation... so 1 as string, casted to string, will match against 1 as int, casted to string....

or not? - what is the difference?? :ehh: :ehh:

visualAd
January 8th, 2005, 06:10 AM
Yes - there seems to be no logical reason to type cast the variables to the same type and then check their type. It would be safe to use the normal comaprison operator.

bigBA
January 8th, 2005, 06:39 AM
i think so, too...

i just thought, that there has to be any reason... but maybe there were only two developers doing the two comparisons.... :)

visualAd
January 8th, 2005, 07:52 AM
Sometimes they are bug work arounds; these should be documented in the source code though. But according to the PHP site and after doing a quick google search I can't seem to find any bugs realting to this subject.

I would leave it as is however, unless you have a special interest in increasing the performance of your script.

bigBA
January 8th, 2005, 12:34 PM
yeah! thx :)