0

I'm trying to do a simple nested array in a session variable. But I'm having a hard time wrapping my head around the logic for the dynamic creation of the arrays.

What I think my code should look like (which I know is wrong, because I want it to be dynamic):

Page 1:

session_start();
$_SESSION['test'] = array();

Page 2:

session_start();
$_SESSION['test'][0] = array('name' => 'john smith', 'age' => '20', 'city' => 'new york');
$_SESSION['test'][1] = array('name' => 'jane doe', 'age' => '42', 'city' => 'seattle');

I want to be able to do a foreach loop to grab the values

foreach($_SESSION['test'] as $test){
echo "Name " . $test['name'];
echo "Age " . $test['age'];
echo "City " . $test['city'];
}
3
  • How do you want it to be dynamic? Are you fetching data from a database? Commented Apr 22, 2014 at 16:55
  • 3
    To make it dynamic, use [] without an index to append new rows: $_SESSION['test'][] = array(....); There's a note about appending in the Arrays manual Commented Apr 22, 2014 at 16:55
  • @MichaelBerkowski I think that's what I'm looking for. Let me go test :) Commented Apr 22, 2014 at 16:57

1 Answer 1

1

You can push to an array like so:

// don't include the index, just use []
$_SESSION['test'][] = array('name' => 'john smith', 'age' => '20', 'city' => 'new york');

Or using array_push():

array_push($_SESSION['test'], array('name' => 'john smith', 'age' => '20', 'city' => 'new york'));
Sign up to request clarification or add additional context in comments.

Comments

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.