Search code examples
phpif-statementpdomodx

if/elseif/else only returning first condition


I am having 2 issues with the following if/elseif/else statement:

$rows = array();
$stmt = $dbconnection->query("SELECT * FROM TABLE_NAME WHERE data_field LIKE 'data_selection'");
if ($stmt) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        array_push($rows, $row);

        if ($row['something '] == 'selection1') {
            $highlightsarray = array("gridHighlights" => 'text option 1 to display on site');
            $highlights = $row + $highlightsarray;
                } elseif ($row['something'] == 'selection2') {
            $highlightsarray = array("gridHighlights" => 'text option 2 to display on site');
            $highlights = $row + $highlightsarray;
                } else {
            $highlights = "<p>default messaging</p>";
        }
        $fields = $highlights; // this is a placeholder for other if statements I need to add
        $output .= $modx->getChunk('chunk_name', $fields);

    }
}
return $output;
}

The first issue I am having is that == is not returning any results, if I change that to = then it somewhat works.

If I make my statement ($row['something '] = 'selection1') (with just =), then it is only returning the first if condition, even if it is not true and should be returning either the elseif or else condition.

Not sure what I am doing wrong here, any assistance is greatly appreciated, thank you.


Solution

  • Closing this question, doing a var_dump as suggested and reviewing my strings got this working. Here is the final code used:

    $rows = array();
    $stmt = $dbconnection->query("SELECT * FROM TABLE_NAME WHERE data_field LIKE 'data_selection'");
    if ($stmt) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        array_push($rows, $row);
    
    var_dump($row); // to review output
    
        if ($row['something '] == NULL) {
            $highlights = $row;
                } elseif ($row['something'] == 'selection2') {
            $highlightsarray = array("gridHighlights" => 'text option 2 to display on site');
            $highlights = $row + $highlightsarray;
                } elseif ($row['something'] == 'selection1') {
            $highlightsarray = array("gridHighlights" => 'text option 1 to display on site');
            $highlights = $row + $highlightsarray;
        }
        $fields = $highlights; // this is a placeholder for other if statements I need to add (like $fields = $highlights + $anotherIfStatement;)
        $output .= $modx->getChunk('chunk_name', $fields);
    
    }
    }
    return $output;
    }