PHP question - arrays?

jjones

Lifer
Oct 9, 2001
15,424
2
0
I have a strings of data recorded in a mySQL database. Example of database fields:
ID, Sample1, Sample2, Sample3, Sample4

I am querying the database to return values for all fields. Then I am using the 4 Sample fields in an array to use in creating options in a drop down list on a form. In other words, the values from sample fields in the database are the options that you will see in the drop down list as follows:

<select>
<option>Sample1 value
<option>Sample2 value
<option>Sample3 value
<option>Sample4 value
</select>

This is easy enough to do with an array. My problem is that some of the fields are empty, Sample fields 1, 2 and 4 may have data but Sample field 3 is empty. With a standard array and executing a while loop, this creates the drop down list as follows:

<select>
<option>Sample1 value
<option>Sample2 value
<option>(blank space)
<option>Sample4 value
</select>

showing a blank space in the drop down list with no value. I would like to create the drop down list without the blank space as follows:

<select>
<option>Sample1 value
<option>Sample2 value
<option>Sample4 value
</select>

which shows that the empty field, Sample3, has not been included.

How can I do this? I know I can do it without using an array and instead using some rather lengthy "if" statements but I want it cleaner than that if possible. I will never know which fields may be empty so I have to account for the possibility that any one or more fields may be empty. Is it possible to do what I want using an array function?
 

docmanhattan

Golden Member
Jul 31, 2001
1,332
0
0
you can loop thru the array using this:

<?php
$option = "<select name=\"blah\">";

foreach($array as $key => $value) {

if($value == "") {

$option .= "<option value=\"$value\">$value";

}

}

$option .= "</select>";

echo $option;

?>
 

jjones

Lifer
Oct 9, 2001
15,424
2
0
Thanks doc; it works great, The only thing I had to change was the if($value == "") statement. It need to be: if($value != "") because I did not want to include empty values.

Anyway, thanks much for the help. I spent a couple hours trying to figure that one out to no avail and I appreciate the assist. :)