1

I am new with php. I want store multidimensional associative array in session and also fetch the value of array from session. But I am not able to do this properly. Below is my code. Thanks.

$myArray = array();
if ((!isset($_SESSION['game']))) {
    echo 'the session is either empty or doesn\'t exist';
} else {
    $myArray = unserialize($_SESSION['game']);
}





    array_push($myArray, new MapResult($keyId, $colorCode, 'NP', $highlow, 'NP', $evenOdd, 'NP'));



session_start();
$_SESSION['game'] = serialize($myArray);
?>
0

1 Answer 1

3

You can't access $_SESSION variables before calling session_start. Also, your serializing of the data is probably pointless. Session data is stored server-side. Serializing would be used if you wanted to dump the session state to a file or to a database or something.

A word of advice...

Instead of littering your code with $_SESSION references, it helps to wrap access in reusable functions. Your code will look nicer and you'll be free to change how session data is stored/accessed at any time without having to refactor your entire app.

// must be called before reading/writing $_SESSION
session_start();

function session_is_initialized() {
  return isset($_SESSION['game']);
}

function session_setup() {
  $_SESSION['game'] = [/* some initial data */];
}

function session_add_item($item) {
  array_push($_SESSION['game'], /* more data */);
}

Now you can write nice clean code

if (!session_is_initialized()) {
  session_setup();
}
session_add_item(['some', 'data']);
Sign up to request clarification or add additional context in comments.

2 Comments

But it giving error Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "MapResult" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in C:\xampp\htdocs\map\search-key.php on line 58
sounds like you didn't require the file that defines MapResult. sounds like you're also still trying that senseless serialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.