Reputation: 29
I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list'])
it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
Upvotes: 0
Views: 75
Reputation: 78994
You are saying that $_POST['check_list']
is an array if implode()
works on it, so no need to loop to get individual items. To implode()
the values:
echo implode(',', $_POST['check_list']);
To implode()
the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach()
iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
Upvotes: 1
Reputation: 298
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key
variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list']
, $_POST['submit2']
seems to be only used to check if is set and nothing else in your piece of code. What foreach
does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key
) in your case. So after the loop, $key
will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode
expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list']
actually an array?
If you're trying to 'glue' together all items of $_POST['check_list']
, you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);
. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Upvotes: 1
Reputation: 8650
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input
if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
Upvotes: 1
Reputation: 1774
implode
function needs array as second argument. You are passing string value as second argument. That's why it's not working.
Upvotes: 0