0

I'm trying to access an array that I stored inside of $_SESSION. I've printed out the count and contents of $_SESSION just before the loop for good measure.

// $_SESSION info.
Length: 4
Array
(
    [loggedIn] => 1 
    [total] => 0 
    [plates] => Array ([0] => plates [1] => 14 [2] => 5) 
    [backpack] => Array ([0] => backpack [1] => 78 [2] => 1)
)

Here we can clearly see that the last two objects are in fact arrays. But, when I try the is_array method,

//PHP code
$length = count($_SESSION);
for ($i = 0; $i < $length; $i++)
{
    if(is_array($_SESSION[$i])){
        echo 'session '.$i.' is an array.<br />';
    }
    else{
        echo 'session '.$i.' is not an array.<br />';
    }
}

all of the objects return false.

session 0 is not an array.
session 1 is not an array.
session 2 is not an array.
session 3 is not an array.

The API says that is_array is supposed to find, «whether the given variable is an array». But, I guess I must be misunderstanding something here...

1
  • 2
    Your array is keyed and not indexed! Use foreach. $_SESSION[0..3] doen't exists. Commented Oct 1, 2012 at 18:23

3 Answers 3

5

Do not use for loop. Use foreach.

foreach ($_SESSION as $key => $val) {
    if (is_array($val)) {
        echo 'session '.$key.' is an array.<br />';
    } else {
        echo 'session '.$key.' is not an array.<br />';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The problem here is that you're trying to iterate through an associative array with numeric indices instead of the appropriate keys. Try this instead:

foreach ($_SESSION as $key => $value)
{
    if(is_array($value)){
        echo 'session '.$key.' is an array.<br />';
    }
    else{
        echo 'session '.$key.' is not an array.<br />';
    }
}

Comments

0

Use:

foreach($_SESSION as $key=>$val){
    if(is_array($val)){
    // code here
    }
}

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.