Skip to content
Advertisement

Simple if statement returning unexpected value

So I have this simple if statement with an input from an array:

var_dump($row);
if($row['Termijn'] == 0){
    $eenmalig = "selected";
}elseif($row['Termijn'] == 1){
    $maandelijks = "selected";
}elseif($row['Termijn'] == 2){
    $jaarlijks = "selected";
}

var_dump() returns:

(array) [12 elements]
0: (integer) 2 
ID: (integer) 2 
1: (string) "anderes"
Naam: (string) "anderes"
2: (string) "0.00"
Beschrijving: (string) "0.00"
3: (string) "0.00"
Prijs: (string) "0.00"
4: (string) ""
Prijsweergave: (string) ""
5: (integer) 2 
Termijn: (integer) 2 

Seems simple right?

Termijn is set to 2 in the array and the if statements set jaarlijks to selected well it doesn’t matter if I use 0, 1 or 2 as inputs it always sets jaarlijks to selected

Advertisement

Answer

Assuming this is still the code you are playing with, you will need to initialise your variables each time round the loop otherwise their values will remain from the previosu iteration of the loop.

$module = $conn->prepare("SELECT * FROM modules");
$modulelist = $module->execute();
$results = $module->get_result();
while ( $row = $results->fetch_assoc() ){
    var_dump($row);

    // clear the variables before using them each time round the loop
    $eenmalig = $maandelijks = $jaarlijks = '';

    if($row['Termijn'] == 0) {
        $eenmalig = "selected";
    }elseif($row['Termijn'] == 1) {
        $maandelijks = "selected";
    }else {
        $jaarlijks = "selected";
    }

    // other code
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement