0

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 ...

3 Answers 3

2
$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 />';
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 />';
}

Comments

0

How about something like this?

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.