PHP comparison does not work

Asked

Viewed 77 times

1

Guys I’m with a problem, the comparison is not working, He should return the message "All right" but ends up returning only the message "Valid only numbers 1 a 60"

    <?php 

    $a = array(1,2,3,4,60);
    $b = count($a);
    $u = count(array_unique($a));

    echo "Original: ".$b."<br>"."Unicos: ".$u."<br>";
    if($b === $u){
        foreach($a as $aceitos){
            if($aceitos > 0 AND $aceitos < 61) {
                echo "Validos apenas números de 1 a 60";
            }else{
                echo "Tudo certo";
            }
        }
        echo "Arrays iguais";
    }else{
        echo "Arrays diferentes";
    }

 ?>

2 answers

2

You just missed there in the condition

    if($aceitos > 0 AND $aceitos < 61) {
            echo "Validos apenas números de 1 a 60";
        }

In this condition, it would be the numbers that would be accepted, in the case between 0 and 60, but the message that you are against, because if you entered this condition, the number is correct. Either you reverse the if with Else, or you do so:

    $a = array(1,2,3,4,60);
    $b = count($a);
    $u = count(array_unique($a));

    echo "Original: ".$b."<br>"."Unicos: ".$u."<br>";
    if($b === $u){
        foreach($a as $aceitos){
            echo $aceitos;
            if($aceitos < 0 || $aceitos > 60) {
                echo "Validos apenas números de 1 a 60<br>";
            }else{
                echo "Tudo certo";
            }
        }
        echo "Arrays iguais";
    }else{
        echo "Arrays diferentes";
    }

 ?>

I hope I’ve helped

1

You got it on parole.

if($aceitos > 0 AND $aceitos < 61)

should be

if($aceitos < 1 OR $aceitos > 60)

  • I really got confused, but it was because I’ve made several changes and nothing works, now for example, even if I fix the comparison if I put "0" in the array it does not identify as an error, it displays the message "all right" and if I put a value "60" in the array it works right, my problem now is about the "0"

  • then you need to use $aceitos < 1 that it will identify the zero as error.

  • I updated the answer.

  • It cannot be less than 1 E greater than 60 at the same time, it is correct to use less than 1 OU greater than 60

  • Well posted @Jadera.Wagner, hadn’t even noticed. Updated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.