remort remort - 1 year ago 68
PHP Question

php variable equality comparison short way

i have a statement in my php:

<? if(isset($_GET['mod']) && ($_GET['mod'] == "category" || $_GET['mod'] == "catalog")) echo 'id="active"'; ?>

i want to learn how to write this types of double comparison in the second part (after &&) like this:

<? if(isset($_GET['mod']) && $_GET['mod'] == ("category" || "catalog")) echo 'id="active"';?>

but it's not working.

there are many pretty if-one-liners in php that i often use in my websites and i wonder to learn one more ))

Answer Source

You can do it like:

if( isset($_GET['mod']) && in_array( $_GET['mod'], array( "category", "catalog") )

As @RepWhoringPeeHaa suggested, stop using short tags as some of the server might not support them.

Also as suggested below, you should try to separate the PHP code outside of the html, like so:


    $active = '';

    $mods = array( "category", "catalog" );
    if ( isset( $_GET['mod'] ) && in_array( $_GET['mod'], $mods ) )
       $active = 'id="active"';


// html
<div <?php echo $active; ?>></div>