I’m trying to complete a simple task where I have an array with 5 values where I need to randomise many times and display the results on a page.
For example, my array could be ('color1','color2','color3','color4','color5').
I need to display, say 50 items on the page with randomised colours, the number of items may increase or decrease depending on other factor.
When an item have been assigned a color then it’ll always be that color, instead of it changing everytime I refresh the page.
I’m currently using array_rand and it’s randomizing the colours every time I refresh the page. shuffle seems to be giving me exactly the same colours on all items.
<?php
class Item{
public $color;
public $colorArray = array('#000','#fff','#0008b2','#0f9d00','#fff600');
public function __construct() {
$this->color = $this->pickColor($this->colorArray);
}
public function pickColor($colors) {
$randNum = array_rand($colors);
$this->color = $this->colorArray[$randNum];
return $this->color;
}
}
?>
Then on my index page I have:
<?php
$item = new Item();
echo $item->color;
?>
I think it will make sense for you:
Test it by refreshing – element 4 will always have the same value: ‘color of carrot’.
This piece of code is based on comments under your question.
UPDATE: I have added some ID to identify that this element’s color was already set, so we can easily store it in session. If you don’t provide any identification you will not be able to do it.
Also I think that colorArray and pickColor method should be static for this class in this case, but I will leave it to you.