note 107234 added to control-structures.switch

From: Date: Thu, 19 Jan 2012 23:25:17 +0000
Subject: note 107234 added to control-structures.switch
Groups: php.notes php.notes 
Request: Send a blank email to php-notes+get-185700@lists.php.net to get a copy of this message
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"; } ---- Server IP: 69.147.83.197 Probable Submitter: 80.101.188.146 ---- Manual Page -- http://www.php.net/manual/en/control-structures.switch.php Edit -- https://master.php.net/note/edit/107234 Del: integrated -- https://master.php.net/note/delete/107234/integrated Del: useless -- https://master.php.net/note/delete/107234/useless Del: bad code -- https://master.php.net/note/delete/107234/bad+code Del: spam -- https://master.php.net/note/delete/107234/spam Del: non-english -- https://master.php.net/note/delete/107234/non-english Del: in docs -- https://master.php.net/note/delete/107234/in+docs Del: other reasons-- https://master.php.net/note/delete/107234 Reject -- https://master.php.net/note/reject/107234 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#185700) next »