0

I will do my best to explain this idea to you. I have an array of values, i would like to know if there is a way to create another array of combined values. So, for example:

If i have this code:

array('ec','mp','ba');

I would like to be able to output something like this:

'ec,mp', 'ec,ba', 'mp,ba', 'ec,mp,ba'

Is this possible? Ideally i don't want to have duplicate entries like 'ec,mp' and 'mp,ec' though, as they would be the same thing

user229044
  • 232,980
  • 40
  • 330
  • 338
Andy Holmes
  • 7,817
  • 10
  • 50
  • 83

3 Answers3

1

You can take an arbitrary decision to always put the "lower" string first. Once you made this decision, it's just a straight-up nested loop:

$arr = array('ec','mp','ba');
$result = array();
foreach ($arr as $s1) {
    foreach ($arr as $s2) {
        if ($s1 < $s2) {
            $result[] = array($s1, $s2);
        }
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • This is great, only thing it doesn't do is out put all array values into one combination (`'ec,mp,ba'`) but i can work on that. Thank you for a quick solution :) – Andy Holmes Jun 06 '15 at 14:20
0

You can do it as follows:

$arr = array('ec','mp','ba', 'ds', 'sd', 'ad');

$newArr = array();

foreach($arr as $key=>$val) {
        if($key % 2 == 0) {
                $newArr[] = $val;
        } else {
                $newArr[floor($key/2)] = $newArr[floor($key/2)] . ',' . $val;
        }
}

print_r($newArr);

And the result is:

Array
(
    [0] => ec,mp
    [1] => ba,ds
    [2] => sd,ad
)
VolenD
  • 3,592
  • 18
  • 23
-1

Have you looked at the function implode

<?php

    $array = array('ec','mp','ba');
    $comma_separated = implode(",", $array);

    echo $comma_separated; // ec,mp,ba
?>

You could use this as a base for your program and what you are trying to achieve.

Dasher Labs
  • 99
  • 1
  • 3
  • 10