2

Is it possible to use the result of an if with an OR statement as a variable for a function?

As example:

$a = true;
$b = false;

if ($a || $b) {
     $this->functionCall($a)
}

Other example:

$a = false;
$b = true;

if ($a || $b) {
    $this->functionCall($b)
}

Third and final exmaple:

$a = true;
$b = true;

if ($a || $b) {
    $this->functionCall($a, $b)
}

So I need to detect what variable is true and pass it as a paramater. Is this even possible?

Any helps is appreciated!

Many thanks in advance

4
  • 1
    Something wrong with standard if() { } else if() { } else { } syntax? Commented Nov 22, 2016 at 13:41
  • In your first and second example, the value you pass to the function is true, does it really matter whether it's $a or $b ? Commented Nov 22, 2016 at 13:42
  • @roberto06 yeah it does :) Commented Nov 22, 2016 at 13:45
  • 2
    Simple solution: pass both variables Commented Nov 22, 2016 at 13:48

2 Answers 2

3

I'd do the logic bit inside a two-parameter function if I were you, as such :

function myFunc($a = false, $b = false) {
    if ($a == true)
        echo 'a';
    if ($b == true)
        echo 'b';
}

myFunc(); // echoes nothing

$a = true;
$b = false;
myFunc($a, $b); // echoes 'a'

$a = false;
$b = true;
myFunc($a, $b); // echoes 'b'

$a = true;
$b = true;
myFunc($a, $b); // echoes 'ab'
Sign up to request clarification or add additional context in comments.

Comments

2

PHP 5.6+ version, filter out the falsely values (you can pass a callback to array_filter for different checks) and use those with the splat operator.

$params = array_filter([$a, $b]);
$this->callFunction(...$params);

No need for any IF checks and confusing in IF assignments.

Explore Variadic functions and Argument unpacking.

1 Comment

Note, you'll need the correct number of params in your callFunction, again you could use function callFunction(...$params){} and examine the params array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.