Kent
Kent

Reputation: 23

Which one is better - Else if or OR

I just want to know the best approach, advise to beginner,regardless both will work and its just preference, Which one is better?

    if ( myVar >= 31 ){
        echo 'Not Valid';
        }
    else if (myVar <=0 ){
        echo 'Not Valid';
        } 
    else{
        echo 'ok';
        }

//OR

    if ( myVar >= 31 || myVar <=0){
        echo 'Not Valid';
        }
    else{
        echo 'ok';
        }

Upvotes: 0

Views: 45

Answers (2)

Nuru Salihu
Nuru Salihu

Reputation: 4928

Each has it's own advantage to me. The second one reduce the code and that is a good thing to do. However in a situation where by you have a lot of comparison to make . i prefer to use the firs one because its easy to debug. Few times i had many problems with misusing '|| and && ' , and this lead to a wrong result often. Imaging if you have a very long comparison and misuses '|| ' in place of '&&'. It sure give headache and takes time to debug sometimes.

However if you use the first one, you know which node to check and where lies the problem. This my idea though the first one is easier to debug in case of error or failure.

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223023

The second form is better, since there is less code duplication.

Upvotes: 1

Related Questions