Last active
December 17, 2023 00:55
-
-
Save macocci7/5ce900cc09d8bfe1c3a7ec2efe5412eb to your computer and use it in GitHub Desktop.
A function to get all pairs of array elements (配列要素の全てのペアを取得する関数)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code results in: