tags:

views:

52

answers:

3

In my code here, I have a CSS class called "active" which I use if the $_GET['page'] == tutorials, php, mysql, etc...

The problem is, even if the 'page' variable is not equal to any of these values, the Tutorials button in this case is still active for some reason.

Any ideas why this would be happening? Am I using the 'or' (||) operand incorrectly?

<?php if($_GET['page'] == 'tutorials' || 'php' || 'mysql' || 'html' || 'css' || 'js') { ?>
      <li class="active"> <?php } else { ?> <li> <?php } ?>

      <a href="index.php?page=tutorials">Tutorials</a>
        <ul>
     <li><a href="index.php?page=php">PHP</a></li>
     <li><a href="index.php?page=mysql">MySQL</a></li>
     <li><a href="index.php?page=html">HTML</a></li>
     <li><a href="index.php?page=css">CSS</a></li>
     <li><a href="index.php?page=js">JS</a></li>
        </ul>
        </li>
+7  A: 

You are using || incorrectly.

You would need to test each whole condition separately to use it that way. So you could do:

<?php if($_GET['page'] == 'tutorials' || $_GET['page'] == 'php' || $_GET['page'] == 'mysql' || $_GET['page'] == 'html' || $_GET['page'] == 'css' || $_GET['page'] == 'js') { ?>

Here's an alternate syntax:

<?php
  if(in_array($_GET['page'], array('tutorials', 'php', 'mysql', 'html', 'css', 'js'))) {
?>

Read more about PHP Control Structures, arrays, and in_array()

artlung
Thanks, this worked!Thanks for the other useful links as well :)
John Wilkes
Good deal. Thought of another way to do this. `<?php switch($_GET['page']): case 'tutorials': case 'php': case 'mysql': case 'html': case 'css': case 'js': ?>``stuff in here``<?php endswitch; ?>`...not pretty though. :-)
artlung
+1  A: 

You can't || strings like that. That's parsed by PHP as being true OR true OR true OR .... The if() has to be re-written as

if ($_GET['page'] == 'tutorials') || ($_GET['page'] == 'php') || etc....)
Marc B
+1  A: 

You are using the || incorrectly.

Basically what you are doing is testing to see if $_GET['page'] == 'tutorials' and that is it - each subsequent 'php', 'mysql' etc evaluates to true. So you get:

$_GET['page'] || true || true || true || true

Simplify it. Put all your stuff in an array, and see if they exist.

$pages = array('tutorials', 'php', 'mysql' /* etc */);
if (in_array($_GET['page'], $pages)) {
    // handle
}
Allyn
You're missing the `needle` parameter in the `in_array` call.
Nick Presta