PDA

View Full Version : if statement always gives true


Kim2
07-02-2008, 03:37 PM
Im trying to avoid writing the same things over and over again with statements. Such as replacing code example 1 with example 2, but without luck. Example 2 always return true.

I know about switch/case, but thats not want Im looking for.

Example 1
$str = "C";
if (($str == "A") || ($str == "B"))

Example 2
$str = "C";
if ($str == ("A" || "B"))

Any ideas why ?
Or how to reduce example 1 to something smaller.

CFMaBiSmAd
07-02-2008, 03:58 PM
Example 2 does not work because the "distributive" property does not work in programming. The posted code OR's "A" with "B", which results in TRUE and then tests if $str == TRUE.

To test if a something exists in a list of values, create an array with the values in it and then use the in_array() function to test if a value is in the array. The in_array section in the php manual contains examples.