0

I have a array in php

array(100,125,135);

I would like to know How I can get all combinations like in the below EG ?

Eg:100=>125,100=>135,125=>100,125=>135,135=>100,135=>125

I Tried something like this

$selected_items = array(100,125,135);
$total = count($selected_items);
$combination = array();
$newcom=0;
    for($i=0;$i<$total;$i++){           
        if($newcom <= $total-1) $newcom = $newcom-1;
        echo  $newcom."-----";
         $combination[$i] = array($selected_items[$i]=> $selected_items[$newcom]);
            $newcom = $i+1;  
    }

But this is not working to get all combinations

Please help me.

2

4 Answers 4

3

Try this

$temp = array(1, 2, 3);
$result = array();

foreach ($temp as $value)
{
    foreach ($temp as $value2)
    {
       if ($value != $value2) $result[$value] = $value2;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

But this is showing only Array ( [1] => 3 [2] => 3 [3] => 2 )
I can't see combination of 1,2
3
$a = array(100,125,135);
$output = array();
foreach ($a as  $first) {
    $arr[$first]=array();
    foreach ($a as $second) {
        if($first != $second)
            $arr[$first][] = $second;
    }

}
$output = $arr;
print_r($output);

4 Comments

That's not a problem. You can always delete your answer here.
@defaultlocale check above one is not correct .. hahha which has 2 votes
@Apptester Array ( [100] => Array ( [0] => 125 [1] => 135 ) [125] => Array ( [0] => 100 [1] => 135 ) [135] => Array ( [0] => 100 [1] => 125 ) )
my bad, sorry. Didn't realize that your answer was different. +1 :)
1

You could use a couple of foreach loops -

$sequence     = [100, 125, 135];
$permutations = [];

foreach ($sequence as $value) {
    foreach ($sequence as $value2) {
        if ($value != $value2) {
            $permutations[] = [$value => $value2];
        }
    }
}

Comments

0

I don't think this can be done. An array contains a key and a value. In your example you want an array where the keys can be the same. You will just overwrite your values So if you run your example the result will be somthing like the following:

 100=>135
,125=>135
,135=>125

A possible solution can be multidimensional arrays:

 100=>array(125, 135)
,125=>array(100, 135)
,135=>array(100, 125)

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.