RepeaterCreeper
RepeaterCreeper

Reputation: 342

Multidimensional PHP Push

if (isset($_POST['callSubmit'])) {
     $vs = 25;
     $callName = $_POST['callName'];
     $callNumber = $_POST['callNumber'];
     $cNumber = array();

     for ($i = 0; $i <= $vs - 1; $i++) {
         array_push($cNumber, array());
     }

     $cNumber[$callNumber - 1][] = $callName;
     print_r($cNumber);
}

This append array is giving me an output of:

Array (
[0] => Array
    (
    )

[1] => Array
    (
    )

[2] => Array
    (
    )

[3] => Array
    (
    )

[4] => Array
    (
    )

[5] => Array
    (
    )

[6] => Array
    (
        [0] => Tested
    )

[7] => Array
    (
    )

[8] => Array
    (
    )

[9] => Array
    (
    )

[10] => Array
    (
    )

[11] => Array
    (
    )

[12] => Array
    (
    )

[13] => Array
    (
    )

[14] => Array
    (
    )

[15] => Array
    (
    )

[16] => Array
    (
    )

[17] => Array
    (
    )

[18] => Array
    (
    )

[19] => Array
    (
    )

[20] => Array
    (
    )

[21] => Array
    (
    )

[22] => Array
    (
    )

[23] => Array
    (
    )

[24] => Array
    (
    )

)

That's the output when it should be appending value everytime I submit a form. Maybe it's because the page refresh when form submits that's why the array gets emptied? Not sure but if anyone could tell me the reason why it's doing so if my assumption of it being emptied when form gets submitted please do let me know.

Alternatives are always accepted!

Upvotes: 1

Views: 28

Answers (1)

Jonathan Lam
Jonathan Lam

Reputation: 17351

You only are appending blank arrays to $cNumber in this line:

array_push($cNumber, array());

You need to change array() to the array of the values you want.

EDIT I realized I didn't answer your question exactly.

You said your code "should be appending value everytime I submit a form".

However, your code is setting $cNumber = array(); every time the script is run (every page reload). In addition, $cNumber is not saved between page load (see Sessions). The page reload is causing the array to reset every time.

You could do this by (using sessions):

<?php

    session_start();
    if(!isset($_SESSION["cNumber"]) {  // ONLY IF array not created create it (to avoid resetting variable every time)
        $_SESSION["cNumber"] = array();
        for ($i = 0; $i <= $vs - 1; $i++) {
            array_push($_SESSION["cNumber"], array());
        }
    }
    $_SESSION["cNumber"][$callNumber - 1][] = $callName;

    print_r($_SESSION["cNumber"]);

?>

Upvotes: 1

Related Questions