0

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

1
  • Why don't you just store the array in the session variable, instead of a string? Commented Jul 16, 2015 at 3:18

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

$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'];

4 Comments

If I use second method, Can I check value is an integer, before store in session?
You can use array_filter($_POST['cuisine'], 'is_int') to get all the integer values in the array.
Barmar, I check it somethig like this, but it seems not working - if (array_filter($cuisine, 'is_int')) { $_SESSION['cuisines'] = $cuisine; }
array_filter doesn't return true or false, it returns an array of all the elements that match the test

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.