Jump to content

i need to combine 5 numbers in sets of 3 ...


keepAway

Recommended Posts

i have an array with 5 numbers...

 

$numbers = array(1 => 4; 
                              2 => 26;
                              3 => 15;
                              4 => 36
                              5 => 9);

 

I need a method  to combine them in sets of three..

For example:

4, 26, 15

4, 26, 36

4, 26, 9

and so on ...

Have ten possible combinations.

Any idea or advice of how i could do this...?

 

I'd think array_chunk will be what you need to accomplish this.

 

http://www.php.net/manual/en/function.array-chunk.php

 

<?php
$numbers = array(1 => 4; 
                              2 => 26;
                              3 => 15;
                              4 => 36
                              5 => 9);
print_r(array_chunk($numbers, 3));
?>

I've tried it and I get this output:

$numbers => Array (2)
(
|    ['0'] => Array (3)
|    (
|    |    ['0'] = Integer(1) 4
|    |    ['1'] = Integer(2) 26
|    |    ['2'] = Integer(2) 15
|    )
|    ['1'] => Array (2)
|    (
|    |    ['0'] = Integer(2) 36
|    |    ['1'] = Integer(1) 9
|    )
)

 

I haven't tried it, not sure how it'll work with keys, but if your array looked like this:

$array = array( 4, 26, 15, 36, 9);

Then it should work fine.

It's hard to give you something here without you writing out the 10 combinations you want. Is 4, 9, 9 good? Is 26, 4, 9 good?

 

Will this work:

<?php
$numbers = array(1 => 4, 2 => 26, 3 => 15, 4 => 36, 5 => 9);
echo '4, 26, 15, 36, 9<br><br>';

for($i = 2; $i < 6; $i++)
{
$start = $i + 1;
for($j = $start; $j < 6; $j++)
{
	$str = $numbers[1].','.$numbers[$i].','.$numbers[$j];
	echo $str,'<br>';
}
}
?>

This thread is marked SOLVED, but the solution is not here. So I'll take a second stab even though you didn't  answer my question:

<?php
$numbers = array(1 => 4, 2 => 26, 3 => 15, 4 => 36, 5 => 9);
echo '4, 26, 15, 36, 9<br><br>';


for($k = 1; $k < 4; $k++)
{
$fins = $k+1;
for($i = $fins; $i < 6; $i++)
{
	$start = $i + 1;
	for($j = $start; $j < 6; $j++)
	{
		$str = $numbers[$k].','.$numbers[$i].','.$numbers[$j];
		echo $str, '<br>';
	}
}
}
?>

 

It outputs

4,26,15
4,26,36
4,26,9
4,15,36
4,15,9
4,36,9
26,15,36
26,15,9
26,36,9
15,36,9

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.