How to make pairs of array values?

Consider the following array:

$input = array('A', 'B', 'C', 'D'); 

I am looking for a way to make a loop, although this array, writing down all possible pairs of two values. In this example: AB AC AD BC BD CD. Please, not that BA is not considered a pair, as AB is already mentioned:

 $output = array( 'A' => 'B', 'A' => 'C', 'A' => 'D', 'B' => 'C', 'B' => 'D' ); 

Any input on how to do this is welcome.

+4
source share
5 answers
 $output=array(); for ($i=0;$i<sizeof($input);$i++) { $k=$input[$i]; for ($j=$i+1;$j<sizeof($input);$j++) { $v=$input[$j]; $output[]=array($k=>$v); } } 

Edit

As of your comment, restructured exit

 $output=array(); //See below for ($i=0;$i<sizeof($input);$i++) { $k=$input[$i]; $v=array(); for ($j=$i+1;$j<sizeof($input);$j++) { $v[]=$input[$j]; } $output[]=array($k=>$v); } 

This will give you "D" => Array () as the last line, if you don't want hti to be changed

 for ($i=0;$i<sizeof($input);$i++) { 

to

 for ($i=0;$i<sizeof($input)-1;$i++) { 
+2
source

something like this might be;

 $input = array('A', 'B', 'C', 'D'); $input_copy = $input; $output = array(); $i = 0; foreach($input as $val) { $j = 0; foreach($input_copy as $cval) { if($j < $i) break; $output[] = array($val => $cval); $j++; } $i++; } $output = array( 0 => array('A' => 'A'), 1 => array('A' => 'B'), 2 => array('A' => 'C'), ... ); 

Please note that your output array is not possible, since the key is overwritten every time

+1
source

This is not possible in PHP, as the PHP array can only have unique keys.

You can get a conclusion like

 $output = array( 'A' => array('B','C','D'), 'B' => array('C','D') ); $input = array('A', 'B', 'C', 'D'); foreach($input as $key => $value){ $tempKey = $key; for($key +1 ; $key < count($input) ; $key++){ $result[$tempKey][] = $input[$key]; } } 
+1
source

You can use this general method:

 function combine($inputArray, &$outputArray, $index, $combLen) { global $outstr; for ($i = $index; $i < count($inputArray); $i++) { $outstr.=$inputArray[$i]; if(strlen($outstr) == $combLen) { $outputArray[]= $outstr; } combine($inputArray, $outputArray, $i + 1, $combLen); $outstr = substr($outstr, 0, strlen($outstr)-1); } } 

Look at ideon

0
source

if you need to work with pairs as arrays

 $pairs = []; foreach($a as $k => $v) { foreach(array_slice($a, $k + 1) as $k2 => $v2) { $pairs[] = [$v, $v2]; } } 
0
source

Source: https://habr.com/ru/post/1395219/


All Articles