felipe
felipe

Reputation: 111

PHP, Send Array with 2 fields as input hidden through Form

I have this array $newArray, it has been built inside of a POST form, so I want to send the whole array in a INPUT as hidden:

Array
(
    [0] => Array
        (
            [day1to7] => 1
            [timeHHMM] => 10:00
        )

    [1] => Array
        (
            [day1to7] => 1
            [timeHHMM] => 11:00
        )

    [2] => Array
        (
            [day1to7] => 1
            [timeHHMM] => 12:00
        )

    [3] => Array
        (
            [day1to7] => 5
            [timeHHMM] => 14:00
        )

)

Could you please help me to know how shall I write it in INPUT?

echo '<input type="hidden" name="newArraySend" value="'. $newArray[day1to7]['timeHHMM'] . '">';  -> this is my wrong try

And also, please let me know how could I receive it?

$newArrayReceived = $_POST['newArraySend']; ->this also is wrong I think

Thank you very much in advance, Felipe

Upvotes: 1

Views: 117

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

To answer the specific question; you could loop and add the hidden inputs:

foreach($newArray as $key => $val) {
    echo '<input type="hidden" name="newArraySend['.$key.'][day1to7]" value="'.$val['day1to7'].'">';
    echo '<input type="hidden" name="newArraySend['.$key.'][timeHHMM]" value="'.$val['timeHHMM'].'">';
}

Then the receiving PHP should use $_POST['newArraySend'] just as you would the original array.

Or just encode the entire array:

$val = htmlentities(json_encode($newArray));
echo '<input type="hidden" name="newArraySend" value="'.$val.'">';

Then decode on the receiving end:

$result = json_decode(html_entity_decode($_POST['newArraySend']), true);

But really this might be better handled with a session:

session_start();
$_SESSION['newArray'] = $newArray;

Then on the receiving end:

session_start();
$result = $_SESSION['newArray'];

Upvotes: 2

Related Questions