Hans Anders
Hans Anders

Reputation: 41

foreach () Error

I'm getting the following warning when running this script:

Warning: Invalid argument supplied for foreach()

This is the script:

$values = array();
foreach ($_POST['rights'] as $right_id)
{
   $values[] = '(' . $id . ', ' . $right_id . ')';
}

$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.

The strange part is that on a different page with the same kind of input it gives no errors.

The question: What is wrong with it?

Upvotes: 1

Views: 109

Answers (4)

Tobias Golbs
Tobias Golbs

Reputation: 4616

The passed array $_POST['rights'] probably is empty.

EDIT:

Like Mark Baker said an empty array is fine. You should go with the other answers.

Upvotes: 0

skparwal
skparwal

Reputation: 1084

As per your statement $_POST['rights'] is not an array.

It is probably a simple string having 1,2,3,4

You need to convert it into an array with explode function.

e.g

$_POST['rights'] = explode(",", $_POST['rights']);

Then your for loop will work.

Upvotes: 0

Matt Harrison
Matt Harrison

Reputation: 13567

foreach must take an array, you're passing it an integer. You can't iterate over an integer.

A wise move might be to check whatever you're about to iterate over is indeed an array:

if(is_array($_POST['rights'])){
    foreach($_POST['rights'] as $value){
        //Whatever you want to do with each $value
    }
}
else {
    //Let the user know it's hit the fan…
    throw new Exception('Help, I\'m not an array :(')
}

PHP docs for arrays: http://php.net/manual/en/language.types.array.php

PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php

Upvotes: 0

som
som

Reputation: 4656

check $_POST['rights']

var_dump($_POST['rights']);

I think $_POST['rights'] is not an array.

Upvotes: 5

Related Questions