3

I am having a hell of a time with this. I have a multidimensional array that I am storing in a session.

$d1 = array(1,2,3,4);
$d2 = array(1,2,3,4,5,6);
$d3 = array(1,2,3,4,5,6,7,8);
$d4 = array(1,2,3,4,5);
$_SESSION['array1'] = array($d1,$d2,$d3,$d4);

what I want to do is remove the $d2 array from the session array1

however when I do something like this

unset($_SESSION['array1'][1]); 

you would think that $_SESSION['array1'] would then = array($d1,$d3,$d4);

however what that does is actually unset the whole session variable.

Then if I try something like

foreach ($_SESSION['array1'] as $k => $v) {
echo "The Key is $k: The Value is $v";
}

however that gives me an error

Invalid argument supplied for foreach()

The only conclusion that I can come to is that the session variable is being completely unset, not that just the specific key is being removed from the array.

is there any way that i can unset a specific value contained within an array that is part of a session variable?

1
  • 1
    There must be something else wrong in the code. Try commenting out the unset(...) line and var_dumping the $_SESSION. Commented Jan 28, 2014 at 0:03

3 Answers 3

1

Code you present works as expected:

header("Content-Type: text/plain");
session_start();
$d1 = array(1,2,3,4);
$d2 = array(1,2,3,4,5,6);
$d3 = array(1,2,3,4,5,6,7,8);
$d4 = array(1,2,3,4,5);
$_SESSION['array1'] = array($d1,$d2,$d3,$d4);
unset($_SESSION['array1'][1]); 
print_R($_SESSION);

Prints:

Array
(
    [array1] => Array
        (
            [0] => Array
                (
                    ...
                )

            [2] => Array
                (
                    ...
                )

            [3] => Array
                (
                    ...
                )

        )

)

So some debugging ideas:

  1. Don't use @session_start.
  2. Set error_reporting(E_ALL)
  3. Configure error reporting in php.ini
  4. Check your cookies to see whether the PHPSESSID cookie was sent at all.
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I fogot to do session_start at the beginning of the script
Please, still have a look at sємsєм's answer. It's good to have arrays ordered like (0, 1, 2 ...). unset does not keep that.
1

Use array_splice as the following code shows:

$_SESSION['array1'] = array_splice($_SESSION['array1'],1,0);

1 Comment

Very good point, unset leaves one offset skipped: (0, 2, ...)
0

How about storing your session variable again:

$_SESSION['array1'] = array($d1,$d3,$d4);

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.