Jump to content

php get random array value


desithugg

Recommended Posts

<?
$number_list = Array("0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29");
$card['0'] = "red";
$card['1'] = "green";
$card['2'] = "yellow";
$card['3'] = "blue";
$card['4'] = "pink";
$card['5'] = "purple";
$card['6'] = "brown";
$card['7'] = "black";
$card['8'] = "white";
$card['9'] = "gray";
?>

Umm I want it to pick a random $card value for each number in the $number_list but I don't want any $card to be used more than 3 times, Im not sure how to do this any idea's where to begin

 

-thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/45878-php-get-random-array-value/
Share on other sites

why would you use two arrays? there's no point. and how are you calling upon these 'card' values? is a user going to click something and get a random card? are you going to loop through them a certain amount of times? always give detailed descriptions of what you want to do. help us help you. this is not a guessing game. i am getting very tired of half-assed posts.       

I think this'll do it

<?php
$number_list = range (0, 29);
$card['0'] = "red";
$card['1'] = "green";
$card['2'] = "yellow";
$card['3'] = "blue";
$card['4'] = "pink";
$card['5'] = "purple";
$card['6'] = "brown";
$card['7'] = "black";
$card['8'] = "white";
$card['9'] = "gray";

$random_cards = array() ;

$count = 0;
foreach ($number_list as $num) {
    if (($k = $count % 10) == 0) 
    {
        shuffle($card);
        reset($card);
    }
    $random_cards[$num] = $card[$k];
    $count++;
} 
echo '<pre>', print_r($random_cards, true), '</pre>'; 
?>

 

I wonder who sucked the jam out of Boo's doughnut :)

This does solve the problem:

<?php
<?php
$card = array('red','green','yellow','blue','pink','purple','brown','black','white','gray');
$random_cards = array() ;
for ($i=0;$i<29;$i++) {
$placed = false;
while (!$placed) {
	$test_card = $card[array_rand($card)];
	if (!in_array($test_card,$random_cards)) {
		$random_cards[] = $test_card;
		$placed = true; }
	else {
		$temp = array_count_values($random_cards);
		if ($temp[$test_card] < 3) {
			$random_cards[] = $test_card;
			$placed = true; }
		}
}
} 
echo '<pre>' . print_r($random_cards, true) . '</pre>'; 
echo '<pre>' . print_r(array_count_values($random_cards),true) . '</pre>';
?>

The second "echo" at the end shows the count of each color.

 

This code has been tested and does work.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.