PHP: Inline Switch Statement (Anonymous Function)

Published on Author YaniLeave a comment

Another reason why I love PHP is its ability to do so many things inline, while keeping the code flow amazingly simple. This is an inline anonymous switch statement, and it allows us to use a switch statement to return us something.

$int = 2;

$value = call_user_func(function($int){
    switch($int){
    case 1: return 'One';
    case 2: return 'Two';
    case 3: return 'Three';
  }
}, $int);

echo $value; //Output: Two

This script allows us to do an inline switch function, by using call_user_func(). And because we’re using it to return something, there’s no need for a break.

 

 

Categories PHP

Leave a Reply

Your email address will not be published. Required fields are marked *