-1

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);
5
  • 2
    I don't know what your'e asking but you can't have any output/html before your session_start Commented Jun 24, 2019 at 15:09
  • Try to assign session's array with $_SESSION["my_array"] = $_SESSION["my_array"] ?? []; Commented Jun 24, 2019 at 15:11
  • This code does nothing: $_SESSION["my_array"] ?? []; Commented Jun 24, 2019 at 15:14
  • 1
    @CristianoCasciotti Your suggestion solves my issues. If you could please move your comment into an answer and add a line explaining why your suggestion works, I will go ahead and approve the answer. Commented Jun 24, 2019 at 15:16
  • This question is effectively a typo question (apart from being a mega-duplicate) because the asker knows how to write an assignment declaration ... they just failed to do so in this one instance. Commented Feb 26 at 10:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
<?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);

?>

1 Comment

if(!is_array($my_array)) { is DEFINITELY not how you check if a variable is declared.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.