I currently have a piece of code that is selecting multiple values from an array and was just wondering how I can switch it over to only picking a single value from an array.
So far I’ve tried changing array_rand($status, rand(2,3)) to array_rand($status, rand(1,1)) but it gives me the error message ** Invalid argument supplied for foreach()**. How can I resolve it?
$dateStart = new DateTime();
$dateStart->setDate(2012, 10, 01);
$dateEnd = new DateTime();
$dateEnd->setDate(2012, 12, 01);
$dates = array();
while ( $dateStart < $dateEnd ) {
$rand = array_rand($status, rand(2,3));
$text = '';
foreach ( $rand as $key ) $text .= $status[$key] . '<br />';
printf("<li><div id='activity_date'>%s</div>
<div id='activity_box'>
<div id='activity_text'>" . $text . ' request</div></div></li>',
$dateStart->format("d/m/Y")
);
$dateStart->modify(sprintf("+%d day",mt_rand(1, 10)));
}
If you want to keep your foreach, you have to ensure that you get an array back from
array_rand. One way would be like this:If you’re always going to want only one random array member, then @Gianps has the better approach. Lose the
foreach.