Reputation: 2926
I have an array and it looks like this.
[cuisine] => Array
(
[0] => 36
[1] => 12
[2] => 2
[3] => 4
[4] => 41
[5] => 22
)
So now I need to store these values in SESSION
. Something like this
$_SESSION['cuisine'] = 36, 12, 2, 4, 41, 22
This is how I tried it, But it doesn't work for me.
if (isset($_POST['cuisine'])) {
$cuisine = $_POST['cuisine'];
$noCuisine = count($cuisine);
if($noCuisine >= 1) {
$cuisines = '';
for($i=0; $i < $noCuisine; $i++) {
$cuisines .= $noCuisine[$i] . ", ";
}
echo $cuisines;
$_SESSION['cuisines'] = $cuisines;
} else {
$error_alert[] = "Please select at least one Cuisine.";
}
} else {
$error_alert[] = "Cuisine field can NOT be empty";
}
Can anybody tell me whats the wrong with this? Thank you
Upvotes: 0
Views: 24
Reputation: 701
Make sure you call session_start()
Use $_SESSION['cuisine'] = implode(',', $cuisine)
instead of these statements:
$cuisines = '';
for($i=0; $i < $noCuisine; $i++) {
$cuisines .= $noCuisine[$i] . ", ";
}
echo $cuisines;
$_SESSION['cuisines'] = $cuisines;
Upvotes: 2
Reputation: 780673
$noCuisines[$i]
is wrong. $noCuisines
is a number, not an array. It should be $_POST['cuisine'][$i]
.
But that whole loop is unnecessary, since PHP provides a built-in function implode
for doing this.
$cuisines = implode(', ', $_POST['cuisine']);
You could also just store the array in the session variable, rather than converting it to a string:
$_SESSION['cuisines'] = $_POST['cuisine'];
Upvotes: 0