Skip to content
PHP Logo

How can a hidden field be used to add a value to an array in PHP?

To add a value to an array in PHP using a hidden field, you can pass the value through a form submission and retrieve it using the $_POST superglobal. You can then use this value to add to the array using array_push or direct assignment.

php
<form method="post">
    <input type="hidden" name="hidden_value" value="new_value">
    <input type="submit" value="Submit">
</form>

<?php
$array = []; // initialize an empty array

if(isset($_POST['hidden_value'])) {
    $new_value = $_POST['hidden_value'];
    array_push($array, $new_value);
}

print_r($array); // output the updated array
?>