How to insert into a table all combination of values in PHP arrays?

To insert all combinations of values from PHP arrays into a database table, you can use nested foreach loops to generate the Cartesian product. This technique creates every possible combination of values across multiple arrays.

Let's say we have the following arrays −

$name1 = ["John", "Mike"];
$name2 = ["David", "Sam"];
$name3 = ["Bob", "Adam"];

Example

Here's how to generate SQL INSERT statements for all combinations ?

<?php
$name1 = ["John", "Mike"];
$name2 = ["David", "Sam"];
$name3 = ["Bob", "Adam"];

foreach ($name1 as $n1) {
    foreach ($name2 as $n2) {
        foreach ($name3 as $n3) {
            echo "INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('$n1', '$n2', '$n3');<br>";
            echo "<br>";
        }
    }
}
?>

Output

INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('John', 'David', 'Bob');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('John', 'David', 'Adam');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('John', 'Sam', 'Bob');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('John', 'Sam', 'Adam');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('Mike', 'David', 'Bob');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('Mike', 'David', 'Adam');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('Mike', 'Sam', 'Bob');
INSERT INTO `student_details` (`name1`, `name2`, `name3`) VALUES ('Mike', 'Sam', 'Adam');

How It Works

The nested loops iterate through each array sequentially. For each element in the first array, it combines with every element in the second array, and then with every element in the third array. This generates all possible combinations (2 × 2 × 2 = 8 combinations in this example).

Conclusion

Using nested foreach loops is an effective way to generate all combinations of array values for database insertion. This approach works well for a small number of arrays with reasonable sizes.

Updated on: 2026-03-15T09:29:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements