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

PHPServer Side ProgrammingProgramming

For this, use the foreach loop and insert into statement in order to insert all combinations of values in PHP arrays.

Let’s say we have the following arrays −

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

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?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');
";          echo "<br>";       }    } } ?> </body> </html>

Output

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');
raja
Updated on 12-Oct-2020 13:14:21

Advertisements