'Foreach not returning if value not found

foreach seems to skip element if not found. Is there any way to force it to return a back up value if not found? I tried to use coalesce to no avail...it will return period if found, otherwise, skips it and move on to checking for next element.

$periods = ['October 2021', 'November 2021', 'December 2021'];

foreach ($periods as $k=>$p) {
     $test = $mysqli->query("select coalesce(period, '$p') as period, coalesce(match_date, 'not found') as match_date from table where period = '$p'");  
     while($row = mysqli_fetch_array($test)) {
       echo $row['period']. '-'. $row['match_date']. '<br>'  ;
        } 
    }


Solution 1:[1]

Found a way by creating first a table and inserting all the periods with a foreach

$reference = $mysqli->query("create temporary table reference (period varchar(15), match_date datetime); ");
foreach ($periods as $k=>$p) {
        $insert = $mysqli->query("insert into reference (period) 
        values ('$p')");
}

Then I use left join with coalesce

$reference2 = $mysqli->query("select ref.period as period, coalesce(tb.match_date, 'not found') as match_date 
FROM reference as ref 
LEFT JOIN table as tb
ON ref.period = tb.period");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Naim