How to solve an elseif that needs to be unique?

6

I want to create a page where when a checkbox is checked, a message is printed, but if all checkbox is checked, print another message.

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <title>Form de exemplo com checkboxes</title>
        <meta charset="utf-8">
    </head>
    <body>
        <form action="" method="post">
            <p>
                <input type="checkbox" name="bike" value="on">eu tenho uma bike
            </p>
            <p>
                <input type="checkbox" name="car" value="on">eu tenho um carro
            </p>
            <p>
                <input type="submit" value="RLRLRLRL" />
            </p>
        </form>
    </body>
</html>
<?PHP
#$_POST['bike'] = ( isset($_POST['bike']) ) ? true : null;
#$_POST['car']  = ( isset($_POST['car']) )  ? true : null;
#var_dump($_POST);

$bike = $_POST['bike'];
$car = $_POST['car'];
if($bike) {
    echo "Olar, eu tenho uma bike";
} elseif ($car) {
    echo "Olar, eu tenho um carro";
} elseif ($car || $bike) {
    echo "Olar, eu tenho os dois";
}

?>
    
asked by anonymous 15.12.2015 / 20:11

2 answers

5

In this particular case the first two conditions are wrong, because it should only be executed if the can is unique, then the condition has to ensure that it has nothing else. There is an error in the last one because it will print if you have either, not both, solution:

if($bike && !$car) {
    echo "Olar, eu tenho uma bike";
} elseif ($car && !$bike) {
    echo "Olar, eu tenho um carro";
} elseif ($car && $bike) {
    echo "Olar, eu tenho os dois";
}

You have other ways to solve this, but this is the closest you've written.

    
15.12.2015 / 20:17
3

Since the values of the checkboxes are the same, another way to solve this is to combine array_keys() to get all the keys of the values ( on ) found, and check the amount with count() .

//equivalente os checkboxs marcados pelo $_POST
$itens = ['bike' => 'on', 'car' => 'on'];
//$itens = ['bike' => 'on']; //outro teste
$marcados = array_keys($itens, 'on');

if(count($marcados) === 1 ){
    echo 'eu tenho '. $marcados[0];
}else if(count($marcados) === 2){
    echo 'tenho ambos, bike e carro';
}
    
15.12.2015 / 20:30