I know the title is not very clear so here it's in code:
function output($selector){
$one = 1;
$two = 2;
$there = 3;
return ? //should return 1 without if or switch statement
}
echo output('one');
If this is possible, how?
Use a variable variable by prefixing the $selector variable with another $:
return $$selector;
Remember to do sanity checks and/or implement default values, so you don't end up generating unnecessary undefined variable errors and such from within your function.
I personally don't like the idea of using variable variables.
Why not just use an array?
function output($selector){
$choices = array(
'one' => 1,
'two' => 2,
'there' => 3,
);
return $choices[$selector];
}
or if your values aren't set in stone:
function output($selector){
// Complex calculations here
$one = 1;
$two = 2;
$there = 3;
return array(
'one' => $one,
'two' => $two,
'there' => $there,
)[$selector];
}
(Yes, I realize this is pretty similar to using a switch statement)
function output($selector){
$one = 1;
$two = 2;
$there = 3;
return $$selector;
}
echo output('one');
But it's not most clever thing.