note 104490 modified in control-structures.switch by danbrown
| From: | danbrown@php.net | Date: | Mon, 20 Jun 2011 15:40:03 +0000 |
| Subject: | note 104490 modified in control-structures.switch by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180790@lists.php.net to get a copy of this message | ||
I often find myself wanting an inline-switch statement (like the ?: for inline if) or
"choose" function, to pick a single value out of a list based on a variable index... just
a convenience function really, but I like compact code...
<?php
function iswitch( $index, $OPTIONS ) {
return @$OPTIONS[$index-1];
}
?>
usage:
<?php echo iswitch( $roll, array( 'rock', 'paper', 'scissors' ) );
?>
I know there is a function for returning a random element from an array, and on a pre-defined array
you can pull the item at a given index. But there is no method for quickly grabbing item x out of a
list inline. (unless there are only 2 options, then the ?: operator works fine)
--was--
I often find myself wanting an inline-switch statement (like the ?: for inline if) or
"choose" function, to pick a single value out of a list based on a variable index... just
a convenience function really, but I like compact code...
function iswitch( $index, $OPTIONS ) {
return @$OPTIONS[$index-1];
}
usage:
echo iswitch( $roll, array( 'rock', 'paper', 'scissors' ) );
I know there is a function for returning a random element from an array, and on a pre-defined array
you can pull the item at a given index. But there is no method for quickly grabbing item x out of a
list inline. (unless there are only 2 options, then the ?: operator works fine)
http://php.net/manual/en/control-structures.switch.php