Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter any given number of html tags through php

I'm working on a project in which I want to display randomly any given number of results suppose, I have six <html> tags of image and I only want to display three randomly so that every time we refresh the page it show randomly any three image out of any six

I'm using html code for an example

<html>
  <body>
    <div class=1>
      <a href="http://example1.com">
        <div>
          <img src="image1.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example2.com">
        <div>
          <img src="image2.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example3.com">
        <div>
          <img src="image3.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example4.com">
        <div>
          <img src="image4.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example5.com">
        <div>
          <img src="image5.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example6.com">
        <div>
          <img src="image6.jpg">
        </div>
      </a>
    </div>
  </body>
</html>

Out of this Six Images I only want to show any three Images Each time through php. Is it possible and how can I do that? Hope you may find any better solution. Also i want to display Other tags like link inthe image and some more tags so that i can display images in a better way through css so I think it can be done by switch statement more easily

like image 246
learner Avatar asked Aug 25 '15 18:08

learner


1 Answers

Let's say you have a array with all the images. From that list, we randomly get the keys for 3 of the images. We then through a loop echo out the img tag:

<html>
<body>
<?php
$images = [
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    'image4.jpg',
    'image5.jpg',
    'image6.jpg'
];

// Selects 3 random array values and returns the key for each value
$randomkeys = array_rand($images, 3);

// Here we loop through the given index keys from the $images array.
// For each key we will then get the value from $images with the index $key
foreach ($randomkeys as $key) {
    // I end with PHP_EOL (End of line) so the source code will look a bit prettier.
    echo "<div class=\"image\"><a href=\"{$images[$key]}\"><img src=\"{$images[$key]}\"></a></div>".PHP_EOL;
}
?>
</body>
</html>

If something was unclear, let me know

Edit 1: Added more tags
It's not hard to add more tags to the output. If you know how to echo string and variables you should be able to easy add more tags or change them the way you want.

As you can see in the update I have added the class image to the , and made the link to the same path as the image so when you click it it will just open the image in the same window.

like image 88
Morten Avatar answered Oct 15 '22 10:10

Morten