Search code examples
phpternary

How to use PHP if/else Ternary for two sets of possibilities


I am currently using something like:

<?=($d === 'bar' || $d === 'foo') ? 'response' : null ?>

To create logic if $d is either 'bar' and 'foo', then return 'response' string. Is there a more elegant way to write this?


Solution

  • You have already written the elegant way. You can use the PHP in_array() function, The in_array() function searches an array for a specific value.

    Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

    <?=(in_array($d, ['foo', 'bar'])) ? 'response' : null ?>
    

    You can make this code even better for readability

    <?php $foo_bar = ["foo", "bar", "bla", "blaa"]; ?>
    
    <?=(in_array($d, $foo_bar)) ? 'response' : null ?>