note 107234 deleted from control-structures.switch by tularis

From: Date: Fri, 20 Jan 2012 17:40:24 +0000
Subject: note 107234 deleted from control-structures.switch by tularis
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-185705@lists.php.net to get a copy of this message
Note Submitter: cmanley ---- I scribbled this functional version of the switch statement to keep my code compact. See test example at the bottom that also shows the advisable style to use to keep code readable. /** * Function version of the switch statement. * * @param mixed $value the value to test * @param (even number of key value pairs) * @param mixed $default * @return mixed */ function switcher(/* variable argument list */) { $args = func_get_args(); if (count($args) < 4) { throw new InvalidArgumentException('At least 4 arguments must be given'); } if (count($args) & 1) { throw new InvalidArgumentException('You must pass an even number of arguments'); } $i = 0; $test = $args[$i++]; for (; $i < count($args) - 1; $i += 2) { if ($test == $args[$i]) { return $args[$i+1]; } } return $args[count($args) - 1]; } foreach (array(null, 's', 'xl', 'xxxl') as $size_code) { $size_desc = switcher( $size_code, // test value null , 'microscopic', 's' , 'small', 'm' , 'medium', 'l' , 'large', 'xl' , 'extra large', 'xxl' , 'huge', "You're off the scale dude!" // default ); print "Size '$size_code' has description '$size_desc'\n"; }

« previous php.notes (#185705) next »