Check if any string has a length, concatenate or use OR?

I have 5 strings I need to check the length of in an if conditional, which is true if any of the string lengths != 0.

Normally you'd see this:

if(strlen($1) != 0 || strlen($2) != 0 || strlen($3) != 0 || strlen($4) != 0 || strlen($5) != 0){}

but I was sitting here thinking it feels (whether it is or not is a different matter) inefficient to have all those OR clauses.

So, I tried:

if(strlen($1.$2.$3.$4.$5) != 0){}

and of course it works. However, I am wondering if there is any reason I should not concatenate these strings together in a strlen to check, whether it be performance or potential logical issue. Seeing as all that needs to be done is check whether any string has length, I don't see a downside.

3 answers

  • answered 2017-01-11 14:23 Landaida

    If it were in javascript I'd see only a problem if one these values is undefined when you need to concatenate

  • answered 2017-01-11 14:23 Gayan

    I think it's with your preference.

    But the readability of what you are tring to say could be changed according to what you are using.

  • answered 2017-01-11 14:23 Toto

    Doing some benchmarks with:

    $a = $b = $c = $d = $e = '';
    
    $t = microtime(true);
    for ($i = 0 ; $i < 1000000; $i++) {
        if(strlen($a) != 0 || strlen($b) != 0 || strlen($c) != 0 || strlen($d) != 0 || strlen($e) != 0){}
    }
    echo 'using || : ',(microtime(true) - $t),"\n";
    
    $t = microtime(true);
    for ($i = 0 ; $i < 1000000; $i++) {
        if(strlen($a) != 0 or strlen($b) != 0 or strlen($c) != 0 or strlen($d) != 0 or strlen($e) != 0){}
    }
    echo 'using or : ',(microtime(true) - $t),"\n";
    
    $t = microtime(true);
    for ($i = 0 ; $i < 1000000; $i++) {
        if(strlen($a.$b.$c.$d.$e) != 0){} 
    }
    echo 'concat : ',(microtime(true) - $t),"\n";
    

    I get:

    run #1:

    using || : 0.1004638671875
    using or : 0.066226959228516
    concat : 0.030498027801514
    

    run #2:

    using || : 0.088317155838013
    using or : 0.082902908325195
    concat : 0.06523609161377
    

    run #3:

    using || : 0.081311225891113
    using or : 0.064895153045654
    concat : 0.028335809707642
    

    run #4

    using || : 0.099178075790405
    using or : 0.093825101852417
    concat : 0.048026084899902
    

    run #5:

    using || : 0.091998100280762
    using or : 0.064527034759521
    concat : 0.031124114990234
    

    Conclusion:

    Concatenate seems quicker than the others 2 or 3 times.