How do I handle multi-dimensional arrays sent via $_POST?

Handling multi-dimensional arrays with $_POST involves accessing nested arrays sent from an HTML form. Here’s an example:

<form method="post" action="process.php">
    <label for="items">Items:</label>
    <input type="text" name="items[0][name]" placeholder="Item 1 name">
    <input type="text" name="items[0][quantity]" placeholder="Item 1 quantity">
    <input type="text" name="items[1][name]" placeholder="Item 2 name">
    <input type="text" name="items[1][quantity]" placeholder="Item 2 quantity">
    <input type="submit" value="Submit">
</form>

In process.php, access the data:

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $items = $_POST["items"];
    foreach ($items as $item) {
        $name = $item["name"];
        $quantity = $item["quantity"];
        echo "Item Name: " . htmlspecialchars($name) . ", Quantity: " . htmlspecialchars($quantity) . "<br>";
    }
}
?>

Make sure to use htmlspecialchars to escape output for security.

0 likes

Top related questions

Related queries

Latest questions