TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Conditional doesn't trigger error, but doesn't work? (http://www.talkphp.com/general/3249-conditional-doesnt-trigger-error-but-doesnt-work.html)

delayedinsanity 08-17-2008 02:17 AM

Conditional doesn't trigger error, but doesn't work?
 
So in my effort to reduce using functions such as preg_match, I tried this little bit of code in a method today:

PHP Code:

        if ($list_type != ('categories' || 'versions'))
        {
            
trigger_error('Invalid list type'E_USER_NOTICE);
            return;
        } 

This doesn't produce any errors or notices, but neither does it work as I hoped it would. How come? I'm using the following instead...

PHP Code:

        if (! in_array($list_type, array('categories''versions')))
        {
            
trigger_error('Invalid list type'E_USER_NOTICE);
            return;
        } 

...but you would think if PHP accepted the original as valid code, it would produce some kind of result.
-m

Theo 08-17-2008 02:34 AM

Its the brackets. ( 'categories' || 'versions' ) would evaluate to TRUE on its own - so the comparison you're actually doing is:

PHP Code:

if( $list_type != true ){...} 

It looks like what you actually want is:

PHP Code:

if ($list_type != 'categories' 
      
&& $list_type != 'versions'))
        {
            
trigger_error('Invalid list type'E_USER_NOTICE);
            return;
        } 

Which should work as you expect.

delayedinsanity 08-17-2008 02:57 AM

Yeah I had it working that way originally, then I decided to see if I could find crafty new ways of doing it, just to see what was possible.

I guess while I know it doesn't work, it doesn't fully make sense to me the reasoning why. In english, I would read that as ( IF variable NOT EQUAL TO (string OR string) ), not ( IF variable NOT EQUAL TO true ). See what I mean?
-m

Theo 08-17-2008 03:31 AM

Think of it like maths - everything in brackets gets evaluated first i.e.

PHP Code:

10
* (4) = 14 

In the same way the expression in brackets gets evaluated before being compared to $list_type. Since neither 'category' or 'versions' evaluate to false, the result of ('categories' || 'versions') is true. This is what then gets compared to $list_type.

Edit:

I would read it as:

IF variable NOT EQUAL TO (string OR string)

in the same way as you, but I would see that:

(string OR string) == true

since everything in brackets gets evaluated first.


All times are GMT. The time now is 09:41 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0