Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

displaying random images on page


5 Posts   1213 Views


15 June 2010 at 4:23am Community Member, 103 Posts


From elsewhere on the forums I've put together this function:

function RandomImages(){

$items = DataObject::get("Image","ParentID=6", false, "")->toArray();
$random_images = new DataObjectSet();
while($random_images->Count() <=1)
$random_index = rand(0,sizeof($items)-1);
$random_images->push($items[$random_index]); //<-Problematic line of code
return $random_images;

and I'm displaying them in my template like so:

<% control RandomImages %>
<a class="thickbox" href="$Filename" >
<img src="<% control SetWidth(220) %>$URL<% end_control %>" alt="$Title" />
<% end_control %>

My pages display properly most of the time, however every once in a while I will get an error '[Notice] Undefined Offset'. I suspect that the problem might be that it only occurs when the same random value is chosen twice in a row and that the 'unset($items[$random_index]);' line is what is causing the error. Once taking this line out, I cannot recreate the error, but instead on occasion I get the same 2 pictures on the page. What would be the proper way to avoid the same random numbers?



4 March 2011 at 12:18am Community Member, 126 Posts

in case someone's still interested:
using 'unset' won't rearrange the indexes in the array. use array_splice instead.


4 March 2011 at 1:13am Community Member, 215 Posts

function RandomImages(){
$limit = 50;
$items = DataObject::get("Image", "ParentID=6", "RAND()", null, $limit);
return $items;


4 March 2011 at 2:05am Community Member, 126 Posts

i guess this will give you duplicates, no?


7 May 2011 at 3:02am (Last edited: 7 May 2011 3:04am), Community Member, 37 Posts

"in case someone's still interested:
using 'unset' won't rearrange the indexes in the array. use array_splice instead.

the link is no best... i think...

Not understand how relolve problem with array_splice MY CASE:

function RandomPerguntasItems()
      $items = $this->Problemas()->toArray();
      $random_perguntas = new DataObjectSet();

      while($random_perguntas->Count() <= ($list_dim-1) )
         $random_index = rand(0,sizeof($items)-1);
         array_splice($items , count($items), 5 );
         //if($items[$random_index]< $random_perguntas->Count()){$random_perguntas->Count() + $items[$random_index];}
      return $random_perguntas;