Home > Backend Development > PHP Tutorial > How to Calculate the Cartesian Product of Multiple Arrays in PHP?

How to Calculate the Cartesian Product of Multiple Arrays in PHP?

Barbara Streisand
Release: 2024-11-14 12:15:02
Original
909 people have browsed it

How to Calculate the Cartesian Product of Multiple Arrays in PHP?

Cartesian Product of Multiple Arrays: A Comprehensive Solution

When dealing with multiple arrays, there may arise a need to generate a table containing every possible combination of elements from these arrays, while avoiding repetitions. This mathematical operation is known as the Cartesian product.

To address this challenge in PHP, consider utilizing the following function:

function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

$cross = array_cartesian(
    array('apples', 'pears',  'oranges'),
    array('steve', 'bob')
);

print_r($cross);
Copy after login

This function takes variable-length arguments, each representing an array. It recursively calculates the Cartesian product by selecting an element from the first array and combining it with all possible Cartesian products of the remaining arrays.

The result is a nested array containing every unique combination of elements from the input arrays. In the given example, the Cartesian product of two arrays will produce:

Array 0            Array 1
apples             steve
apples             bob
pears              steve
pears              bob
Copy after login

This solution is not only effective for arrays with two dimensions but can also be extended to handle any number of arrays. It provides a concise and elegant way to solve the Cartesian product problem in PHP.

The above is the detailed content of How to Calculate the Cartesian Product of Multiple Arrays in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template