Skip to content

Instantly share code, notes, and snippets.

@macocci7
Last active December 17, 2023 00:55
Show Gist options
  • Save macocci7/5ce900cc09d8bfe1c3a7ec2efe5412eb to your computer and use it in GitHub Desktop.
Save macocci7/5ce900cc09d8bfe1c3a7ec2efe5412eb to your computer and use it in GitHub Desktop.
A function to get all pairs of array elements (配列要素の全てのペアを取得する関数)
<?php
/**
* returns all pairs
* @param array $items
* @return array
*/
function pairs(array $items)
{
if (count($items) < 2) {
throw new \Exception("Too few elements.");
}
$pairs = [];
$lastIndex = count($items) - 1;
for ($x = 0; $x < $lastIndex; $x++) {
for ($y = $x + 1; $y <= $lastIndex; $y++) {
$pairs[] = [$items[$x], $items[$y]];
}
}
return $pairs;
}
$items = ['A', 'B', 'C', 'D', 'E'];
$pairs = pairs($items);
array_map(function ($pair) {
echo implode(', ', $pair) . "\n";
}, $pairs);
@macocci7
Copy link
Author

This code results in:

$ php -f pairs.php 
A, B
A, C
A, D
A, E
B, C
B, D
B, E
C, D
C, E
D, E

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment