Home > Backend Development > PHP Tutorial > How to Generate Cartesian Products of Multiple Arrays in PHP?

How to Generate Cartesian Products of Multiple Arrays in PHP?

Patricia Arquette
Release: 2024-11-15 14:03:03
Original
249 people have browsed it

How to Generate Cartesian Products of Multiple Arrays in PHP?

Creating Cartesian Products of Multiple Arrays in PHP

Consider a PHP array structure like the following:

$array[0][0] = 'apples';
$array[0][1] = 'pears';
$array[0][2] = 'oranges';

$array[1][0] = 'steve';
$array[1][1] = 'bob';
Copy after login

Objective: To generate a tabulated list of all possible combinations of elements from these arrays, without duplication.

Solution:

The concept of generating all possible combinations from multiple arrays is known as the "Cartesian product." There are several methods to achieve this in PHP.

One approach is to utilize PHP's array functions. The following code snippet implements the Cartesian product using func_get_args() and recursion:

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;
}
Copy after login

To use this function, pass an arbitrary number of arrays as arguments. For example, to generate the Cartesian product of the above arrays:

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

The result, stored in $cross, will be an array containing all possible combinations:

print_r($cross);
Copy after login

Output:

Array (
    [0] => Array (
        [0] => apples
        [1] => steve
    )
    [1] => Array (
        [0] => apples
        [1] => bob
    )
    [2] => Array (
        [0] => pears
        [1] => steve
    )
    [3] => Array (
        [0] => pears
        [1] => bob
    )
)
Copy after login

The above is the detailed content of How to Generate Cartesian Products 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