Page 1 of 1

Receiving error when appending to $_SESSION array

Posted: Tue Nov 30, 2004 12:48 pm
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?

Posted: Tue Nov 30, 2004 1:33 pm
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"
?>

Posted: Tue Nov 30, 2004 2:07 pm
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?

Posted: Tue Nov 30, 2004 3:26 pm
by xisle
the warning indicates that $_SESSION['itn'] is currently a string,
it cannot be an array as well.