Given an array containing some elements, the task is to find all possible pairs of array elements using PHP.
Examples:
Input: arr = [1, 2, 3]
Output: [[1, 2], [1, 3]]
Input: arr = [1, 2, 3, 5]
Output: [[1, 2], [1, 3], [1, 5], [2, 3], [2, 5], [3, 5]]
Table of Content
Approach 1: Using Nested for Loops
Nested loop is the most straightforward method to find all possible pairs in an array. This method involves iterating through the array with two loops and selecting unique pairs of elements
Example:
PHP
<?php function getAllPairs( $arr ) {
$pairs = [];
$len = count ( $arr );
for ( $i = 0; $i < $len - 1; $i ++) {
for ( $j = $i + 1; $j < $len ; $j ++) {
$pairs [] = [ $arr [ $i ], $arr [ $j ]];
}
}
return $pairs ;
} // Driver code $arr = [1, 2, 3, 4, 5];
$pairs = getAllPairs( $arr );
print_r( $pairs );
?> |
Output:
Array (
[0] => Array(
[0] => 1
[1] => 2
)
[1] => Array(
[0] => 1
[1] => 3
)
[2] => Array(
[0] => 1
[1] => 4
)
[3] => Array(
[0] => 1
[1] => 5
)
[4] => Array(
[0] => 2
[1] => 3
)
[5] => Array(
[0] => 2
[1] => 4
)
[6] => Array(
[0] => 2
[1] => 5
)
[7] => Array(
[0] => 3
[1] => 4
)
[8] => Array(
[0] => 3
[1] => 5
)
[9] => Array(
[0] => 4
[1] => 5
)
)
Approach 2: Using array_reduce() Function
The array_reduce() function can be used to generate all possible pairs. This approach involves iterating through the array and creating pairs using a combination of array_map() and array_slice() functions.
Example:
PHP
<?php function getAllPairs( $arr ) {
$pairs = array_reduce ( $arr ,
function ( $result , $item1 ) use ( $arr ) {
$pairs = array_map (
function ( $item2 ) use ( $item1 ) {
return [ $item1 , $item2 ];
}, array_slice ( $arr ,
array_search ( $item1 , $arr ) + 1)
);
return array_merge ( $result , $pairs );
}, []);
return $pairs ;
} // Driver code $arr = [1, 2, 3, 4, 5];
$pairs = getAllPairs( $arr );
print_r( $pairs );
?> |
Output
Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 1 [1] => 3 ) [2] => Array ( ...