Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if not equal(!=) and or (||) issue. Why doesnt this work?

Tags:

php

I know this is simple PHP logic but it just won't work...

 $str = "dan";
 if(($str != "joe") 
   || ($str != "danielle")
   || ($str != "heather")
   || ($str != "laurie")
   || ($str != "dan")){         

 echo "<a href='/about/".$str.".php'>Get to know ".get_the_author_meta('first_name')." &rarr;</a>";
                  }

What am I doing wrong?

like image 499
Greg Thompson Avatar asked Nov 27 '22 20:11

Greg Thompson


2 Answers

I am not exactly sure what you want, but that logic will always evaluate to true. You might want to use AND (&&), instead of OR (||)

The furthest statement that is ever tested is ($str != "danielle") and there are only two possible outcomes as PHP enters the block as soon as a statement yields true.

This is the first:

$str = "dan";

$str != "joe" # true - enter block
$str != "danielle" #ignored
$str != "heather" #ignored
$str != "laurie" #ignored
$str != "dan" #ignored

This is the second:

$str = "joe";

$str != "joe" # false - continue evaluating
$str != "danielle" # true - enter block
$str != "heather" #ignored
$str != "laurie" #ignored
$str != "dan" #ignored

If the OR was changed to AND then it keeps evaluating until a false is returned:

$str = "dan";

$str != "joe" # true - keep evaluating
$str != "danielle" # true - keep evaluating
$str != "heather"  # true - keep evaluating
$str != "laurie" # true - keep evaluating
$str != "dan"  # false - do not enter block

The solution doesn't scale well though, you should keep an array of the exclude list and check against that do:

$str = "dan";
$exclude_list = array("joe","danielle","heather","laurie","dan")
if(!in_array($str, $exclude_list)){          
    echo " <a href='/about/".$str.".php'>Get to know ".get_the_author_meta('first_name')." &rarr;</a>";
}
like image 196
Gazler Avatar answered Dec 18 '22 21:12

Gazler


Another approach is

$name = 'dan';
$names = array('joe', 'danielle', 'heather', 'laurie', 'dan');

if(in_array($name,$names)){  
    //the magic
}
like image 39
joakimdahlstrom Avatar answered Dec 18 '22 22:12

joakimdahlstrom