views:

1308

answers:

3

I have this drop down list, displaying all the files from a folder, one of which will be selected for use. Is there a way to show which file is selected when you load the page? at the moment it says "select a file" every time.

<select name="image" type="text" class="box" id="image" value="<?=$image;?>">
<option value='empty'>Select a file</option> 
<?php

$dirname = "images/";
$images = scandir($dirname);

// This is how you sort an array, see http://php.net/sort
natsort($images);

// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; }
    }
?>
</select>
+1  A: 

I get the feeling SO is writing your application for you bit by bit...

anyway,

<?php
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'"
            . ($file == $image ? " selected" : "")
            . ">$file</option>\n";
    }
}
?>

nickf
+1  A: 

use the "selected" tag on your option for the file that is selected

first check to see which file is selected from the post or get (it's unclear what action the form is taking from your post.. assuming get)

use the ternary operator in your loop:

$selected = $_GET['image'] == $file ? "selected" : "";

print "<option $selected value='$file'>$file</option>\n";
Zak
+1  A: 

And similarly to Zak's and NickF's answers, you can use

selected="selected"

in your option tag if you like to go for XHTML.

(On a side-note, my new reputation does not allow me to add comments to answers yet.)

Philipp Lenssen