dimanche 1 août 2021

Following code is not reaching the else statement

Disclaimer: I'm new to programming, this is a simple exercise I'm doing so go easy on me.

The following code is not reaching (printing) the else statement. Any insight is much appreciated.

$number = '1120011';

    // Decimal check
    if($number[0] == '+' && $number[1] == '0'){
        echo "Error: Can't assign a plus sign on a leading zero!";
    // Leading zero check    
    } elseif($number[0] == '+' || $number[0] == '-'){
        echo "Number is decimal";
    // Binary check    
    } elseif (preg_match('~^[01]+$~', $number)) {
        echo "Number is binary";
    // Code not executing here. For e.g. $number = 1120011    
    } else {
        "Number is non binary";
    }

Another question:

Why is the following 'if' not working properly (if I replace it in the code above). I guess it has something to do with bad usage of operators.

if($number[0] == '+' || $number[0] == '-' && $number[1] == '0')

Thanks in advance! :)

Aucun commentaire:

Enregistrer un commentaire