Page 1 of 1
what's the best way to pair elements in an array
Posted: Sat Mar 31, 2007 3:39 pm
by s.dot
Code: Select all
$participants = array(1,2,3,4,5,6,7,8,9,10);
//shuffle 10 times
for($i=0; $i<10; $i++)
{
shuffle($participants);
}
//make pairs
$pairs = array();
I need to pair them up. So I'll have 5 total pairs out of that array. What's the best way to do that?
Posted: Sat Mar 31, 2007 3:40 pm
by feyd
Posted: Sat Mar 31, 2007 3:45 pm
by s.dot
I got this
Code: Select all
$j = 0;
for($i=0; $i<(count($participants)/2);$i++)
{
$pairs[] = array($participants[$j], $participants[$j + 1]);
$j = $j+2;
}
Didn't think of using array_chunk(). Mine just looked ugly so I thought there had to be a less messy way
Code: Select all
$pairs = array_chunk($participants, 2);
looks much better.
Posted: Sat Mar 31, 2007 4:14 pm
by Kieran Huggins
I assumed you want to randomize the pairing, which may or may not be the case... If you do, call shuffle($participants) first.
Posted: Sat Mar 31, 2007 4:38 pm
by s.dot
Kieran Huggins wrote:I assumed you want to randomize the pairing, which may or may not be the case... If you do, call shuffle($participants) first.
I did
My script ended up like this.
Code: Select all
<?php
//array of all participants
$participants = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
//random number to shuffle
$rand = mt_rand(10, 100);
//shuffle $rand times
for($i=0; $i<$rand; $i++)
{
shuffle($participants);
}
//make pairs
$pairs = array_chunk($participants, 2);
//list pairs
foreach($pairs AS $pair)
{
echo '<p>'.$pair[0].'<br />'.$pair[1].'</p>';
}
?>
Posted: Sat Mar 31, 2007 5:08 pm
by John Cartwright
Code: Select all
//random number to shuffle
$rand = mt_rand(10, 100);
//shuffle $rand times
for($i=0; $i<$rand; $i++)
{
shuffle($participants);
}
Whats the point? Simply call shuffle() once and let that be the end of it

Posted: Sat Mar 31, 2007 11:08 pm
by s.dot
adds a bit of randomness?
Posted: Sat Mar 31, 2007 11:13 pm
by John Cartwright
shuffling once is no more random than shuffling a billion times.
Posted: Sat Mar 31, 2007 11:15 pm
by s.dot
Ah, I didn't know that.
I figured it was like a deck of cards. When you first open them up, they're in order. Shuffle once and they'll be randomized, but some still in order.
Posted: Sat Mar 31, 2007 11:26 pm
by John Cartwright
nope, but if you want to use the shuffling of a deck of cards analogy, imagine throwing a deck of cards in the air and picking them up after.
Posted: Sat Mar 31, 2007 11:28 pm
by s.dot
Cool.
Posted: Sun Apr 01, 2007 5:11 am
by Kieran Huggins