Try something like this:
<form action="fishing.php" method="post">
<?php
$fish = array(
'catfish.gif' => 'catfish',
'lmbass.gif' => 'large-mouth bass',
'smbass.gif' => 'small-mouth bass',
'shiner.gif' => 'shiner',
'perch.gif' => 'perch',
'pickerel.gif' => 'pickerel',
'minnow.gif' => 'minnow',
'sunfish.gif' => 'sunfish'
);
$rand = array_rand($fish);
$sImageOut = "";
//check the image
// - yes, error supression is normally evil
// - and assigning variables in this way isn't exactly pretty
// ... but it works
if(list($iImgX, $iImgY, $iImgType, $sImgAttr) = @getimagesize(__DIR__ . '/img/' . $rand)) {
$sImageOut = "<div><img src=\"img/{$rand}\" alt=\"{$fish[$rand]}\" style=\"width: {$iImgX}px; height: {$iImgY}px; border: 1px solid #cccccc;\" /></div>\n";
}
//output
echo "<p>Nice one! You caught a {$fish[$rand]}!</p>\n{$sImageOut}";
?>
<p><input type="submit" class="btn btn-primary" value="Go Fishing!"></p>
</form>
Since the image name is the key and array_rand()
returns the key ... $rand
contains the image filename.
I'm using getimagesize()
in there so that if, for some reason your image doesn't exist, it won't create "duff" output - not the tidiest code but it works as an example.