Toolbox
Toolbox

Reputation: 2493

Array push only works when array is predefined with value

I am looking to create an array that keeps growing with one random number every time the PHP scripts runs. If I secure that the [$_SESSION["my_array"] has a value predefined then it works with increase per each script round.

However, if I do not pre-define the above mentioned array, then a random number is being created but the array does not grow in amount of stored digits.

Question: Is there a way of avoiding the need of populating the array at start? I would like the array to start with being empty.

<pre>

    <a href="session_destroy.php">Destroy session</a>

    <?php
        session_start();

        $_SESSION["my_array"] ?? [];
        $my_array = $_SESSION["my_array"];

        $new_random_value = rand(1, 6);

        array_push($my_array, $new_random_value);

        $_SESSION["my_array"] = $my_array;


        var_dump($my_array);

        var_dump($_SESSION);

    ?>  

My [destroy_session] file:

<?php

    session_start();
    $_SESSION = array();
    session_destroy();

    var_dump($_SESSION);

Upvotes: 0

Views: 55

Answers (2)

Cristiano Casciotti
Cristiano Casciotti

Reputation: 1026

You're not initializing the session array, you have to initialize it like this:

$_SESSION["my_array"] = $_SESSION["my_array"] ?? [];

Otherwise you don't have a start value in your array, and that's the reason why your push doesn't grow the array.

Upvotes: 2

Beneris
Beneris

Reputation: 637

<?php
    session_start();

    $my_array = $_SESSION["my_array"];
    if(!is_array($my_array)) {
        $my_array = array();
    }

    $new_random_value = rand(1, 6);
    array_push($my_array, $new_random_value);
    $_SESSION["my_array"] = $my_array;

    var_dump($my_array);
    var_dump($_SESSION);

?>

Upvotes: 0

Related Questions