Receiving error when appending to $_SESSION array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
voltrader
Forum Contributor
Posts: 223
Joined: Wed Jul 07, 2004 12:44 pm
Location: SF Bay Area

Receiving error when appending to $_SESSION array

Post by voltrader »

Code: Select all

$_SESSION['itn'][]=$session_array;
Fatal error: [] operator not supported for strings in ... on line 88

Shouldn't this append the array $session_array to $_SESSION['itn'] array?
Last edited by voltrader on Tue Nov 30, 2004 2:04 pm, edited 1 time in total.
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

itn is an array key - you can set it directly to any other array without the final square brackets...

Code: Select all

<?php
$myarray = array("foo"=>"", "bar"=>"bar_data");

$otherarray = array("data1"=>"Maugrim", "data2"=>"Reaper");

$myarray['foo'] = $otherarray;

echo $myarray['foo']['data1'];

// echoes "Maugrim"

?>
On the other hand if you want 'itn' key to point to an array of arrays - i.e. keys default to 0, 1, 2, 3, etc. as you append more arrays - just use array_push()

Code: Select all

<?php
$myarray = array("foo"=>array());

$otherarray = array("data1"=>"Maugrim", "data2"=>"Reaper");

array_push($myarray['foo'], $otherarray);

echo $myarray['foo']['0']['data1'];

// echoes "Maugrim"
?>
User avatar
voltrader
Forum Contributor
Posts: 223
Joined: Wed Jul 07, 2004 12:44 pm
Location: SF Bay Area

Post by voltrader »

Thanks Reaper.

This relates to another thread I started earlier. I'm trying to retain checkbox values POSTed from another page in an array within a $_SESSION array.

Code: Select all

$posted_array = array ( [0] => 12, [1] => 13) ;

array_merge($_SESSION['itn'], $posted_array);

// this generates a 'Warning: array_push(): First argument should be an array' error
are arrays within arrays are not supported for the superglobal $_SESSION, or do I first have to ensure that an array within an array has been created?
User avatar
xisle
Forum Contributor
Posts: 249
Joined: Wed Jun 25, 2003 1:53 pm

Post by xisle »

the warning indicates that $_SESSION['itn'] is currently a string,
it cannot be an array as well.
Post Reply