Dizzi
Dizzi

Reputation: 747

Help with php random random array

I need help with an array problem I have, so far I have this:

$array1 = array('foo1', 'foo2', 'foo3', 'foo4', 'foo5');

$array2 = array('newfoo1', 'newfoo2', 'newfoo3', 'newfoo4', 'newfoo5');

$random1 = array_rand($array2);
$random2 = $array2[$random1];

foreach($array1 as $key){
 echo $key . '<br />';
 echo $random2 . '<br /><br />';
}

which outputs:

foo1
newfoo4

foo2
newfoo4

foo3
newfoo4

foo4
newfoo4

foo5
newfoo4

But I want "newfoo4" (array2) to be a random item so it would output somethng like this:

foo1
newfoo3

foo2
newfoo4

foo3
newfoo1

foo4
newfoo5

foo5
newfoo2

rather then the same,

BUT also allow duplicates of array2 so array1 and array2 do not have to have the same amount items in their arrays ....

so for instance if array1 had 5 items and array 2 only 3 items end result output could be:

foo1
newfoo3

foo2
newfoo1

foo3
newfoo3

foo4
newfoo2

foo5
newfoo3

...I hope this makes sense to someone ...

Upvotes: 0

Views: 341

Answers (3)

jwerre
jwerre

Reputation: 9624

How about something like this?

foreach($array1 as $key){
 $rand_num = rand(0, count($array2));
 echo $key . '<br />';
 echo $array2[$rand_num] . '<br /><br />';
}

Upvotes: 0

jfoucher
jfoucher

Reputation: 2281

Try putting this line

$random2 = $array2[array_rand($array2)];

into your foreach loop, like so:

foreach($array1 as $key){
    $random2 = $array2[array_rand($array2)];
    echo $key . '<br />';
    echo $random2 . '<br /><br />';
}

Upvotes: 0

Radek
Radek

Reputation: 8386

$array1 = array('foo1', 'foo2', 'foo3', 'foo4', 'foo5');
$array2 = array('newfoo1', 'newfoo2', 'newfoo3', 'newfoo4', 'newfoo5');

foreach($array1 as $key){
    echo $key . '<br />';
    echo $array2[array_rand($array2)] . '<br /><br />';
}

Upvotes: 2

Related Questions