As with most web developers about half of my code is collecting information via forms (the other half is presenting that information). When a form is submitted there are a variety of variables that I might want to display back to the user in the form elements. The code snippet below simplifies how I handle which variable to display.
Previously my code for an input field would have used a lot of nested inline if statements to determine which variable to fill the field with. It might have looked something like this:
echo '<input type="text" name="email" value="' . (($_POST['email']) ? $_POST['email'] : (($user['email']) ? $user['email'] : 'Email') . '" />';
The code above would show the posted email address first, and if that’s not present defer to one from the database. If neither of those are present then it would display a label, “Email” in this case.
That’s a nightmare to manage, and it looks nasty. So I wrote a function called postOrNot($post, $other) which simplified the inline if statement a touch. If the first variable was present, it was displayed, if not then it would display the 2nd.
With the introduction of “func_get_args()” to the function it can handle any number of arguments, falling over to each one in turn, and finally returning false if none are present.
function ifelse(){
if(func_num_args() < 2) trigger_error("ifelse() requires 2 or more arguements", E_USER_ERROR);
else {
$args = func_get_args();
foreach($args as $arg){
if($arg) return $arg;
}
return false;
}
}
It's a function that I use pretty much every day and saves me lines and lines of code.