Reputation: 1550
After applying what wrapping objects using math operator, I just tought it will be over. But no. By far.
<?php
$faces= array(
1 => '<div class="block">happy</div>',
2 => '<div class="block">sad</div>',
(sic)
21 => '<div class="block">angry</div>'
);
$i = 1;
foreach ($faces as $face) {
echo $face;
if ($i == 3) echo '<div class="block">This is and ad</div>';
if ($i % 3 == 0) {
echo "<br />"; // or some other wrapping thing
}
$i++;
}
?>
In the code I have to put and ad after the second one, becoming by that the third object. And then wrap the three all in a <div class="row">
(a br after won't work out by design reasons). I thought I will going back to applying a switch, but if somebody put more elements in the array that the switch can properly wrap, the last two remaining elements are wrapped openly.
Can i add the "ad" to the array in the third position? That would make things simplier, only leaving me with guessing how to wrap the first and the third, the fourth and the sixth, an so on.
Upvotes: 2
Views: 430
Reputation: 173652
First, insert the ad:
array_splice($faces, 2, 0, array('<div class="block">this is an ad</div>'));
Then, apply the wrapping:
foreach (array_chunk($faces, 3) as $chunk) {
foreach ($chunk as $face) {
echo $face;
}
echo '<br />';
}
Upvotes: 1
Reputation: 9380
You could just split the array in two, insert your ad and then append the rest:
// Figure out what your ad looks like:
$yourAd = '<div class="block">This is and ad</div>';
// Get the first two:
$before = array_slice($faces, 0, 2);
// Get everything else:
$after = array_slice($faces, 2);
// Combine them with the ad. Note that we're casting the ad string to an array.
$withAds = array_merge($before, (array)$yourAd, $after);
I think nickb's note about using the comparison operator rather than assignment will help get your wrapping figured out.
Upvotes: 1