hans hans - 1 month ago 8
PHP Question

Php combine an array of values into an array with double combinations string

How i can combine ad array of values into an array with double combination string without duplications ?

For example, if i have something like:

array('one','two','tre','four','five');


I want to obtain an array of combinations like this ('one / two') just one time and not also ('two / one').

In this way i wanto to get something similar to:

array('one/two', 'one/tre', 'one/four', 'one/five', 'two/tree','two/four' .......


Suggestions ?

Answer Source

You can do it with this code. It won't show two/one, three/two, etc (that's how I understood it):

<?php
$array = array('one','two','tre','four','five');
$newArray = [];
foreach ($array as $el) {
    foreach ($array as $el2) {
        if ($el === $el2) continue;
        $newArray[] = $el."/".$el2;
    }
    array_shift($array); // remove the element we just went through
}
print_r($newArray);

Demo