Answer the question
In order to leave comments, you need to log in
What is the most concise and understandable way to pass one of two variables to one function argument, which can be either an array or a logical expression?
Hello. An interesting question has arisen. There is a certain function, it has conditionally one argument:
function f($a) {
...
}
// заранее известно, что одна из переменных будет массивом/объектом, а другая - true/false
if ($x) {f($x)}
else if ($y) {f($y)}
f($x || $y);
Answer the question
In order to leave comments, you need to log in
Perhaps you are approaching the problem in the wrong way. I would get rid of the function that takes a boolean on Mondays, an array on Tuesdays, and an object on the rest of the week, since this function takes on too much responsibility, and would switch instead to three different functions, the first of which takes a boolean argument, the second takes an array, and the third takes an object.
The code is written not only to be executed, but also to be read by other developers, and such a feature is clearly not conducive to the speed of studying the code and making changes to it.
Maybe the ternary operator
will suit you.
And the short version
is f($x ?: $y)
In this case, if $x is TRUE, then $x and $y will be passed to f otherwise.
Examples
true ?: 'test' - будет true
false ?: 'test' - будет 'test'
'' ?: true - будет true
'test' ?: true - будет 'test'
// Комбинирование
false ?: [] ?: 'test' - будет 'test'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question