Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>";
}
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading