Question

I have code like this:

$finalResult = true;

$finalResult = $finalResult && function_01();
// some code here
$finalResult = $finalResult && function_02();
// some many lines of code here
$finalResult = $finalResult && function_XX();


And I'm looking for a way how to shorten the code (just for a human-readibility reasons) to something like:

$finalResult = true;

$finalResult &&= function_01();
// some code here
$finalResult &&= function_02();
// some many lines of code here
$finalResult &&= function_XX();

But of course this doesn't work and operator &= is not for boolean values, but for binary.

How should I do this ?
Thanks.

Was it helpful?

Solution 3

OK, after all it seems I will not get it any simpler than original.

For those of you who don't understand why I want to have it in some "short" form - only reason was to have it shorter and nicer. Just the same reason why there is possibility to write $a += 3 just for beauty.

Anyway, thanks to everybody :)

OTHER TIPS

$names = array('function01','function02'...);
$result = true;
foreach($names as $caller)
{
  $result = $result && $caller();
}

otherwise instead of $caller() you could look for call_user_func ( http://us3.php.net/call_user_func )

it's not really fantastic, but it's shorter :/ not a big deal

edit: uhm... i guess that after your edit this solution is not more functional... should i delete it ?

I would also reconsider the logic of your code by adding a class that makes these checks: if all the checking logic is in a class whose purpose is just that you could surely benefit of readability

Stormsson's but improved - finish as soon as you know the result:

$names = array( 'function01','function02'... );
$result = true;

foreach( $names as $caller )
{
    if ( $result == false ) break; // short circuit

    $ret = $caller()
    if ( $ret == false )
    {
        $result = false;
        break; // short circuit
    }

    $result = $result && $ret;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top