What about this, using the ternary ?:
operator :
function addString($text, $add, $type = 'prepend') {
return $type=='prepend' ? $add . $text : $text . $add;
}
Note : I actually would probably not use that -- and stay with a classic if/else : not a one-liner, not as nice to read... But probably a lot easier to understand ; and having understandable code is what trully matters.
Edit after the comment : if you want to make sure that the $type
is either 'append'
or 'prepend'
, and still want a one-liner, you could go with something like this :
function addString($text, $add, $type = 'prepend') {
return ($type=='prepend' ? $add . $text : ($type=='append' ? $text . $add : ''));
}
But your code will become harder to read -- and it's probably time to go with something that's longer than just one line of code, and easier to understand.
For example, why not something like this :
function addString($text, $add, $type = 'prepend') {
if ($type === 'prepend') {
return $add . $text;
} else if ($type === 'append') {
return $text . $add;
} else {
// Do some kind of error-handling
// like throwing an exception, for instance
}
}
After all, the number of lines has pretty much no impact on the way the code is executed -- and, again, what matters is that your code is easy to understand and maintain.