Open In App

How to Get All Possible Pairs in Array using PHP ?

Last Updated : 16 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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]]

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:

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:


Output
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
        )

    [2] => Array
        (
     ...

Approach 3: Using Combinatorial Generator with Recursive Function

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:


Output
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
        )

    [2] => Array
        (
     ...

Approach 4: Using a Combination of array_map() and array_slice()

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


Output
All possible pairs:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
        )

    [2] => A...



Next Article

Similar Reads