W3docs

How to use php array with sql IN operator?

You can use the implode() function to convert the PHP array into a string of comma-separated values, and then use that string in the SQL query with the IN operator.

You can use the implode() function to convert the PHP array into a string of comma-separated values, and then use that string in the SQL query with the IN operator. Here is an example:

Example of using the implode() function to convert the PHP array

<?php

$arr = [1, 2, 3, 4];
// Sanitize input: cast all values to integers to prevent SQL injection
$arr = array_map('intval', $arr);
$in = implode(',', $arr);
$sql = "SELECT * FROM table WHERE column IN ($in)";

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can then execute the $sql query using your database connection.

Example of executing the query in PHP

<?php

// Assume $conn is a valid mysqli connection
$result = mysqli_query($conn, $sql) or die('Query failed: ' . mysqli_error($conn));

Also make sure to properly sanitize the input array before using it in the query. For integer arrays, array_map('intval', $arr) works well. For string arrays, use mysqli_real_escape_string() or dynamic prepared statement placeholders to prevent SQL injection.