0

I am using a foreach to loop through image. There are maximum four images and minimum 1 image. For example if there are two image (= two loops) i want to tell the foreach he needs to loop two times again and echo some placeholder pictures.

Heres my foreach:

<?php foreach($users as $k => $v) {?>
<img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php } ?>

Outputs (two loops):

<img src="/images/user_0.jpg" alt="" title="" />
<img src="/images/user_1.jpg" alt="" title="" />

but the new script should output:

<img src="/images/user_0.jpg" alt="" title="" />
<img src="/images/user_1.jpg" alt="" title="" />
<img src="/images/user_placeholder.jpg" alt="" title="" />
<img src="/images/user_placeholder.jpg" alt="" title="" />

dont forget its possible that $users can have x entries (0-4)

ggzone
  • 3,661
  • 8
  • 36
  • 59
  • So you want x number of user images to be output to the browser, and x number of placeholders (thus far all identical) immediately after them? – Malovich Apr 26 '12 at 14:58

4 Answers4

4

Use array_fill to fill an array with as many items as needed (since they are all going to be identical) and then print them out.

<?php foreach($users as $k => $v) {?>
<img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php } ?>

<?php
echo implode('', array_fill(0, count($users), 'placeholder image HTML'));

Of course instead of this cuteness you could also use another foreach that prints placeholder image HTML in each iteration.

Update: It turns out there's an even better method:

echo str_repeat('placeholder image HTML', count($users));

PHP really has too many functions to remember. :)

Jon
  • 428,835
  • 81
  • 738
  • 806
  • thanks for this cute solution :) *accept* ... edit: both worked. And i like one-line solutions so im double happy – ggzone Apr 26 '12 at 15:05
0

Use a counter...

<?php
$counter = 0; 
foreach($users as $k => $v) {?> 
    <img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php $counter++;  
} 
while{$counter < 4)
{?>
    <img src="/images/user_placeholder.jpg" alt="" title="" />
<?php } ?>
Matt Moore
  • 581
  • 2
  • 6
0

this should work

$count = 1;
foreach($users as $k => $v) {
?>
    <img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
<?php 
    $count++;
} 

for ($i = $count; $i <= 4; $i++) {
?>
    <img src="/images/user_placeholder.jpg" alt="" title="" />
<?php 
}  
?>
0
<?php 
$placeholders = array();
foreach($users as $k => $v) {?>
    <img src="/images/user_<?php echo $k; ?>.jpg" alt="" title="" />
    <?php 
    $placeholders[] = '<img src="/images/user_placeholder.jpg" alt="" title="" />';
} 
foreach ($placeholders as $placeholder){
    echo $placeholder;
} ?>

As you can see, there are a dozen ways to skin this particular cat.

Malovich
  • 931
  • 1
  • 5
  • 15