![]() |
VOOZH | about |
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
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:
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
)
)
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:
Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 1 [1] => 3 ) [2] => Array ( ...
This method involves creating a recursive function to generate all possible pairs from an array without repeating any combinations. The recursive function works by choosing the first element and then recursively pairing it with each subsequent element in the array, and then moving on to the next element and repeating the process.
Example: Here's how you can use this recursive approach to find all possible pairs in an array:
Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 1 [1] => 3 ) [2] => Array ( ...
Another approach to find all possible pairs in an array is to use a combination of array_map() and array_slice(). This approach utilizes array_map() to iterate over each element and array_slice() to create subarrays for pairing.
Example
All possible pairs: Array ( [0] => Array ( [0] => 1 [1] => 2 ) [1] => Array ( [0] => 1 [1] => 3 ) [2] => A...