PHP Load Image if exist?
I am using this code for a slideshow:
<img src="<?php echo($array[0]); ?>"/>
<img src="<?php echo($array[1]); ?>"/>
<img src="<?php echo($array[2]); ?>"/>
<img src="<?php echo($array[3]); ?>"/>
<img src="<?php echo($array[4]); ?>"/>
<img src="<?php echo($array[5]); ?>"/>
<img src="<?php echo($array[6]); ?>"/>
<img src="<?php echo($array[7]); ?>"/>
I want to show imag开发者_运维百科es, only if they exist. Sometimes the $array has only 5 values.
How is this posible?
You should loop over the array values and echo an image tag for each value:
<?php
foreach($array as $img){
echo '<img src="'.$img.'"/>'."\n";
}
?>
That's the perfect opportunity for a loop. You can either use a for
loop (since your array is numerically indexed) or a foreach
loop.
Using a for
loop:
<?php $count = count($array); for($i = 0; $i < $count; $i++): ?>
<img src="<?php echo($array[$i]); ?>" />
<?php endfor; ?>
In traditional syntax:
<?php $count = count($array); for($i = 0; $i < $count; $i++) { ?>
<img src="<?php echo($array[$i]); ?>" />
<?php } ?>
Using a foreach
loop:
<?php foreach($array as $img): ?>
<img src="<?php echo $img; ?>" />
<?php endforeach; ?>
In traditional syntax:
<?php foreach($array as $img) { ?>
<img src="<?php echo $img; ?>" />
<?php } ?>
Since this is a fairly basic question, I suggest you take the time to read the PHP Documentation chapter about control structures. There are essential. It is available here:
PHP Documentation: Control Structures
foreach($array as $src){ echo "<img src='$src' />"; }
<?php
foreach($array as $img){
if(file_exists($img))
echo '<img src="'.$img.'"/>'."\n";
}
?>
for($i=0;$i<count($array);$i++)
{
?>
<img src="<?php echo($array[$i]); ?>"/>
<?php
}
精彩评论