Jump to content
Killersites Forums

How to Understand $_SESSION with multi-dimensional arrays


Recommended Posts

Hello,

I'm working through the login System using OOP in Stef's course.  In the file m_template.php, there is this line of code:

(Line 58)

function setAlert($value, $type = null)
    {
        if ($type == '') { $type = $this->alertTypes[0]; }
        $_SESSION[$type][] = $value;
    }

I'm trying to see how the highlighted section of code is working.

Ben explains this, but I don't quite understand yet.

First of all, I want to check that my concept of the session variable $_SESSION is correct:

If I unpack a hypothetical $_SESSION variable, it could look something like this:

$_SESSION [

'success' => ['you are logged in']

'warning' =>[ ]

'error' => []

user => 'John'

]

So, $_SESSION is a variable holding an array.  Within that array is another array which could have a key of either success, warning, or error.

$_SESSION might also have other elements in the array like user.

When I write the code $_SESSION[$type][] = $value; I could think of it in this example:

$_SESSION['success'][] = 'you are logged in';

This line of code means that I will be adding to the nested array with the key of 'success'.

So if $_SESSION looked like this instead:

$_SESSION [

'success' => ['logging in is awesome', 'You are so bomb for logging in', 'High Five!', ]

'warning' =>[ ]

'error' => []

user => 'John'

]

I would be tacking on 'you are logged in' like so:

'success' => ['logging in is awesome', 'You are so bomb for logging in', 'High Five!',  'you are logged in']

However, if I left out the brackets like so:

$_SESSION['success'] = 'you are logged in';

then I would over-write the array with the key of 'success' and create this:

'success' => 'you are logged in'

Am I thinking about all of this correctly?

Update: Nov 11, 2020

I wonder if it is a bit unnecessary to have this line of code:

$_SESSION[$type][] = $value (m_template.php, line 58)

rather than this:

$_SESSION[$type]= $value

There doesn't seem to be any circumstance where there is more than one value per key at any given time.

 

 

Edited by Drew2
Link to post
Share on other sites
  • 1 month later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...