1

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 images, only if they exist. Sometimes the $array has only 5 values.

How is this posible?

5 Answers 5

4

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";
}
?>
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1
foreach($array as $src){ echo "<img src='$src' />"; }

Comments

0
<?php
foreach($array as $img){
    if(file_exists($img))
    echo '<img src="'.$img.'"/>'."\n";
}
?>

Comments

0
for($i=0;$i<count($array);$i++)
{
?>
  <img src="<?php echo($array[$i]); ?>"/>
<?php
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.