December 23, 2012

How to print just a few from an array instead of all in php

Question by Marqeeu Rahfis

This is part of the working code that shows the entire array;

$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
echo "<a href="" . $list['name'] . "$startDir"><h4> " . $list['name'] . " </h4></a>";
//    echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";

How do I modify it so that it only displays 10 or 15 list instead of all?

Answer by Starx

If you know the keys or indexes of the array you can do what KingCrunch is doing a lot faster by simple for loop

for($i=0; $i<=14; $i++) {
   // echo $file[$i];
June 28, 2012

random number generation without duplicates

Question by Zendie

I have to show some banners in a webpage.The number of banners will be with in 10 (max 10). I can set the number of banners and each banner folder in database. Banner images are stored in separate server folders based on category. Banners are showing in columns.

My code is,
Here, long1,long2,…long10 are directory names from database

       $files = array();

               $openDir = opendir($dir);
                       while (false !== ($file = readdir($openDir)))
                               if ($file != "." && $file != "..")
                                       $files[] = $file;

mt_srand((double) microtime()*1000000);
 $randnum = mt_rand(0,(sizeof($files)-1));



 $img = $dir."/".$files[$randnum];

  <input type="image" class="advt_image" src="<?=$img;?>" alt="" name=""/>

ex: if there is 7 banner set in database, I have to show 7 banners from different or same folder.(some banners will be from same folder). I need to avoid the duplicate banners each time when I display a webpage.

I have assigned an array to store each random numbers. Do I need to change anything in code? any thought/idea?


Answer by restart

You can remove the image that is displayed from the $files array in the loop. this means you will have to check the length of the array in the loop as well. you could use array_diff for this.

$files = array(...); // this holds the files in the directory
$banners = array();  // this will hold the files to display
$count = 7;
for($i=0;$i<$count;$i++) {
    $c = mt_rand(0,count($files));
    $banners[] = $files[$c];
    $files = array_diff($files, array($files[$c]));

// now go ahead and display the $banners

Answer by Starx

A simple way to solve this problem would be create a array to hold the list of banner than before displaying them.

I didn’t read your code (Sorry), but here is a basic concept, with which this is possible.

$bannerList = array();

//Now, check if the list contains the banner before adding it
while($rows) { //your big list of banners

    if(!in_array($rows['bannerpath'])) {
        $bannerList[] = $rows['bannerpath'];


Please fill the form - I will response as fast as I can!