my code causes the images to appear randomly within the page. But how to insert an "element" (in my case would be a div) between these images?
<?php
$myImagesList = array (
'image1.png',
'image2.png',
'image3.png',
'image4.png'
);
shuffle ($myImagesList);
for ($i=0; $i<4; $i++) {
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
}
?>
Example:
The original code displays the images as follows:
image3.png image4.png image2.png image1.png
F5 refresh page
image2.png image1.png image4.png image3.png
F5 refresh page
image4.png image2.png image3.png image1.png
I needed it this way:
image2.png image1.png
content
image4.png image3.png
F5 refresh page
image4.png image2.png
content
image1.png image3.png
F5 refresh page
image2.png image3.png
content
image4.png image1.png
You would want something like this...
$myImagesList = array (
'image1.png',
'image2.png',
'image3.png',
'image4.png'
);
shuffle ($myImagesList);
$i = 0;
foreach ($myImagesList as $img) {
$i++;
if ($i % 3 === 0) { /* show content */ }
echo '<img src="/image/' . $img . '" width="200" height="140" border="0" />';
}
This will give you the content section every third iteration, no matter the size of the list.
If you want to add a div
(content) between those two pairs of images - add additional condition into your loop:
...
for ($i=0; $i<4; $i++) {
if ($i == 1) echo '<div>some content ...</div>';
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
}
Go with the most readable solution - the one that doesn't make you fall and debug later when changing something.
$splitAtNumber = 2; // or dynamically use count($myImagesList) / 2 or ....
// output first part of the array
for ($i = 0; $i < $splitAtNumber; $i++) {
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
}
// Output your content
echo 'content';
// Output second part of the array
for ($i = splitAtNumber; $i < count($myImagesList); $i++) {
echo '<img src="/image/' . $myImagesList[$i] . '" width="200" height="140" border="0" />';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.