Not a vital question, just wondering if there is any onliner to do this.
function addString($text, $add, $type = 'prepend') {
// oneliner here
return $text;
}
$text = 'World';
addString($text, 'Hello ', 'prepend'); // returns 'Hello World'
addString($text, ' Hello', 'append'); // returns 'World Hello'
Any ideas? : )
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.
return $type == 'prepend' ? $add . $text : $text . $add;
Are you familiar with the . in PHP?
For example:
echo $text . "Hello!";
You could use a ternary operator to achieve this as follows:
function addString($text, $add, $type = 'prepend') {
return $type == 'prepend' ? $add . $text : $text . $add;
}
What the ternary operator is effectively doing is checking the first condition (the one prior to the ?
to see if it evaluates to true. If it does, it sets the return value of the statement to $add . $text
, if not if uses the final block (after the :
) to set the return value to $text . $add
.
As the PHP manual puts it:
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
As such, if someone provides something other than 'prepend
' as the $type
argument's value, then this will always default to the second condition and append.
$text = ($type === 'prepend') ? $add.$text : $text.$add;