Better If Else Statements

Hi! I am not a PHP guy but I know there is a better way to condense my hacked up little PHP snippet into something cleaner.

The context is that I want to get the value of a variable (total 4 values). Depending on the value, I want to display certain content. Below is my first stab (the context is WordPress).

<?php global $wp_query; ?>
<?php if (isset($wp_query->query_vars['inv'])) : ?>
    <h1 style="color:#fff;">
        <?php
            if ($wp_query->query_vars['inv'] == 'yh') {
                echo "Yahoo!";
            }
        ?>
        <?php
            if ($wp_query->query_vars['inv'] == 'bg') {
                echo "Bing Cosby Baby!";
            }
        ?>
        <?php
            if ($wp_query->query_vars['inv'] == 'gg') {
                echo "Google Bitch!";
            }
        ?>
        <?php
            if ($wp_query->query_vars['inv'] == 'tp') {
                echo "Third Party!";
            }
        ?>
    </h1>
<?php endif; ?>

You can use an array

// key => value array
$array = array('yh' => 'Yahoo', 'bg' => 'Bing Cosby Baby!', 'gg' => 'Google Bitch!', 'tp' => 'Third Party!');

// if key is in the array, display the appropriate value, otherwise throw the default value....
if (array_key_exists($wp_query->query_vars['inv'], $array)) {
	echo $array[$wp_query->query_vars['inv']];
} else {
	echo "Invalid Option!";
}
2 Likes

Sweet. Thanks for the comments too - they help me understand the process!

1 Like

Hi conradical,

You could also try using a switch statement as another alternative:

<?php
if (isset($wp_query->query_vars['inv']))
{
        switch($wp_query->query_vars['inv'])
        {
                case 'yh':
                {
                           echo 'Yahoo!';
                           break;
                }
                case 'bg':
                {
                           echo 'Big Cosby Baby!';
                           break;
                }
                case 'gg':
                {
                           echo 'Google Bitch!';
                           break;
                }
        }
}

Cheers

Thanks! Appreciate the alternate solutions as well!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.