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)
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. :)
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 } ?>
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
}
?>
<?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.