2

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.

Community
  • 1
  • 1
DarkGhostHunter
  • 1,521
  • 3
  • 12
  • 23

2 Answers2

1

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.

drewish
  • 9,042
  • 9
  • 38
  • 51
  • You mean `array_splice()`? :) – Ja͢ck Jun 30 '12 at 03:47
  • I'd looked at the docs for array_splice and they don't clearly discuss what happens with a 0 length. It's interesting to see that it works that way. – drewish Jul 01 '12 at 04:09
  • @drewish yes, they only mention the behaviour for positive and negative lengths, though it gets mentioned in the example snippets further down :) – Ja͢ck Jul 01 '12 at 07:17
1

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 />';
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • I think you meant array_splice($faces, 2...) rather than 3. The question asked for how to get it into the third spot where yours would put it into the fourth. – drewish Jul 01 '12 at 04:06
  • It also looks like you could drop the wrapping array for the add. – drewish Jul 01 '12 at 04:10
  • @drewish thanks for the comment, I've applied the position change, but I felt it's better to leave the explicit array cast. – Ja͢ck Jul 01 '12 at 07:15