Search code examples
phphtmltemplates

How do I remove the comma if there is no value?


I have a select field that gets its values from a database table. Not all records in the database have all fields. Some are null. I want my select field to show the name,iata,icao - a combination of these three seperated by a comma. The issue is that some of my fields do not have an icao and some do not have an iaata. Is there a way for me to alter my code such that if there is no icao or iata the comma is ignored.

Please see below:

enter image description here

enter image description here

The code i need to alter is below:

 <select name="airport1" class="airport1" id="airport1">
                    <option selected value="Add">Select Airport</option>

                    <?php
                    $mysqli = NEW MYSQLI("localhost", "root", "", "airports");
                    $resultSet = $mysqli->query("SELECT name,iata,icao 
    FROM airports order by name ASC;
    ");

?>

                    <?php
                    while ($rows = $resultSet->fetch_assoc()){
                        $name = $rows['name'];
                        $iata = $rows['iata'];
                        $icao = $rows['icao'];
                        echo "<option value='$name,$iata,$icao'>$name,$iata,$icao</option>";
                    }
?>

Solution

  • You can check whether iata or icao is null before appending them to the string:

    ...
    while ($rows = $resultSet->fetch_assoc()) {
        $name = $rows['name'];
        $iata = $rows['iata'];
        $icao = $rows['icao'];
    
        $displayValue = $name;
        
        if ($iata) {
            $displayValue .= ", " . $iata;
        }
        
        if ($icao) {
            $displayValue .= ", " . $icao;
        }
    
        echo "<option value='$name,$iata,$icao'>$displayValue</option>";
    }
    ...
    

    OR: You can use implode function to join the non-null values with a comma

    ...
    while ($rows = $resultSet->fetch_assoc()) {
        $name = $rows['name'];
        $iata = $rows['iata'];
        $icao = $rows['icao'];
    
        //create an array of non-null values
        $nonNullValues = array_filter([$name, $iata, $icao]);
    
        //use implode to join the non-null values with a comma
        $displayValue = implode(', ', $nonNullValues);
    
        echo "<option value='$name,$iata,$icao'>$displayValue</option>";
    }
    ...