So I'm trying to store an array in a session, but instead of making it an array it just counts everything up all the time! I just want the value that is done in the session, so I can check if the number isn't done already! There meight be a smarter way to it, but this will do for now!
public function nextNumber($list) {
$i = rand(1, count($list)-1);
echo $list[$i];
if (!in_array($list[$i], Session::get('savedlist'))) {
Session::put('savedlist', Session::get('savedlist') + $list[$i]);
var_dump(Session::get('savedlist'));
return $list[$i];
}
}
And this is my put function
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function get($name) {
return $_SESSION[$name];
}
I don't know if I undersood your question correctly, however I think that the put function needs to be updated:
public static function put($name, $value) {
if(empty($_SESSION[$name])){
// create a new array with the given name
$_SESSION[$name] = array($value);
} else {
// add a new item at the end of the array
$_SESSION[$name][] = $value;
}
}
adding the two square brackets after [$name]
will insert $value
as a new item at the end of $_SESSION[$name]
. Otherwise it will be only a variable, not an array.
Then change the nextNumber($list)
function as follows
change this line:
Session::put('savedlist', Session::get('savedlist') + $list[$i]);
with
Session::put('savedlist', $list[$i]);
So the new value will be put at the end of the savedlist
array.
I can't fully understand what you want to do, but since you accepted @lastYorsh answer, I'll assume you want something like his.
If we assume that Session::get('savedlist')
can return an array then you can't add a number to an array with the +
sign. Session::get('savedlist') + $list[$i]
I think @lastYorsh implementation should also have an if statement
for the case that second argument is an array is_array()
.
Furthermore.
Warning: Cannot use a scalar value as an array
Try this
$_SESSION[$name] = []; // array();
$_SESSION[$name][] = $value;
But then
if (!in_array($list[$i], Session::get('savedlist'))) {
You can't use the in_array
in associative arrays.
That lead us to the conclusion that @lastYorsh answer isn't what you want. Leave your Session
implementations as it is and change this
if (!in_array($list[$i], Session::get('savedlist'))) {
$savedlist = Session::get('savedlist');
array_push($savedlist, $list[$i]);
Session::put('savedlist', $savedlist);