App tester
App tester

Reputation: 139

How to get array combinations in php?

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.

Upvotes: 0

Views: 57

Answers (4)

bhushya
bhushya

Reputation: 1317

$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);

Upvotes: 3

Pardon Me
Pardon Me

Reputation: 31

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];
        }
    }
}

Upvotes: 1

YANTHO
YANTHO

Reputation: 89

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)

Upvotes: 0

slash197
slash197

Reputation: 9034

Try this

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

foreach ($temp as $value)
{
    foreach ($temp as $value2)
    {
       if ($value != $value2) $result[$value] = $value2;
    }
}

Upvotes: 3

Related Questions