ST80
ST80

Reputation: 3893

PHP how to get specific value from array and store in `$_SESSION`

I have an array where I want to fetch a specific value ('created') and store then im a $_SESSION in a new array. How can I achieve that?

my array looks like this

Array
    (
        [0] => Array
            (
                [product_id] => 679
                [quantity] => 1
                [created] => 2018-10-01
            )

        [1] => Array
            (
                [product_id] => 677
                [quantity] => 1
                [created] => 2018-10-05
            )

        [2] => Array
            (
                [product_id] => 678
                [quantity] => 1
                [created] => 2018-10-03
            )

    )

I tried something like:

foreach($created as $i) {
   $values = [$i]['created'];
   echo $values;
}

session_start();
$_SESSION['creation_dates'] = $values;

but that doesn't work.

Can someone help me out?

Upvotes: 1

Views: 41

Answers (1)

msg
msg

Reputation: 8161

You need to start your session first thing, before any output. Your echos are preventing that. You must be getting Notices but not seeing them depending on your error_reporting.

Try this code instead:

session_start();

$values = array();
foreach($creation_dates as $i) {
   $values[] = $i['created'];
}

$_SESSION['creation_dates'] = $values;

print_r($values);
print_r($_SESSION['creation_dates']);

Upvotes: 2

Related Questions