Skip to content

Instantly share code, notes, and snippets.

@timotheemoulin
Created May 1, 2019 12:46
Show Gist options
  • Save timotheemoulin/dd590c4d428e35010c7a242acf0739f2 to your computer and use it in GitHub Desktop.
Save timotheemoulin/dd590c4d428e35010c7a242acf0739f2 to your computer and use it in GitHub Desktop.
Avoid if else structure when possible
<?php
global $i;
$i = 0;
function test() {
global $i;
var_dump(++$i);
return $i;
}
switch (test()) {
case 'foo':
var_dump('this is foo');
break;
case 'bar':
var_dump('this is bar');
break;
case 'baz':
var_dump('this is baz');
break;
default:
var_dump('this is default');
break;
}
$i = 0;
if ('foo' == test()) {
var_dump('this is foo');
} else if ('bar' == test()) {
var_dump('this is bar');
} else if ('baz' == test()) {
var_dump('this is baz');
} else {
var_dump('this is default');
}
/*
The above code will print.
Please avoid using if else structure or at least, store the result of the fuction before.
int(1)
string(15) "this is default"
int(1)
int(2)
int(3)
string(15) "this is default"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment