A section of my site is a blog where I allow comments. Each comment has a thumbnail associated with it. If the commenter is a user, then their profile photo is used. If they are anonymous I have a pre-determined photo in place. I want to be able to randomly generate a thumbnail for these anonymous users, but also have no duplicates.

I asked this question here and now have a random thumbnail being generated, but the problem is that there are still duplicates. And it looks like because the comment.tpl.php file is being read on each comment that the random numbers are not being remembered.

How can Drupal remember the number so that it doesn't use it again?

My Code:

$numbers = range(0, 19);

print "<div id='commenter-picture'>";
print "<img src='member_default_" . array_pop($numbers) . ".png' />";
print "</div>";

1 Answer 1


Haven't tested this, but I think this should work. Remove your first two lines of code and place the following in your theme's template.php file (replace MYTHEME with the machine name of your theme):

function MYTHEME_preprocess_comment(&$vars){ $max = 19; $numbers = $_SESSION['MYTHEME_comment_numbers'] ?: range(0, $max); shuffle($numbers); $vars['number'] = array_pop($numbers); $_SESSION['MYTHEME_comment_numbers'] = count($numbers) ? $numbers : range(0, $max); }

This makes available a $number variable inside your comment.tpl.php file.

Then, replace your last three lines inside comment.tpl.php with:

print "<div id='commenter-picture'>";
print "<img src='member_default_" . $number . ".png' />";
print "</div>";

This will remove already used numbers from your $numbers array until there's none left, and then reset to use the full array again.

  • Thanks @olyN. I am getting an error when trying to run this. Can I run this as it shows or do I need to rename the 'MYMODULE' variable? I am new to PHP so this is a bit over my head. Thanks for the help!
    – Dan
    Jul 3, 2014 at 16:01
  • No worries. Are you adding this into a template file? What's the error you're getting?
    – Ollie
    Jul 3, 2014 at 16:04
  • Well I get the traditional white screen with no CSS styling on the page. I am placing this into my comment.tpl.php template file.
    – Dan
    Jul 3, 2014 at 16:07
  • OK, fixed, I've edited the answer. You should replace MYTHEME with the machine name of your theme. It will probably work anyway, but it's good to use naming conventions. :)
    – Ollie
    Jul 3, 2014 at 16:32
  • The page keeps crashing on this line: $numbers = array_values(array_diff($numbers, $already_used);
    – Dan
    Jul 3, 2014 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.