If array isset, do something?
Question
I am posting multiple checkboxes, and putting them into an array - for example: "tags[]"
When posting them, I am imploding them with commas.
If NO tags are checked on the form, and then posted, I get errors as the script is trying to implode something that isn't there.
I have tried using something like this:
if (isset($_POST['tags'])){
$tags = implode(", ", noescape($_POST['tags']));
}
What is the best way to check if it exists, then implode it?
isset, array_key_exists?
Solution
You could do it in one line, in this situation isset
and array_key_exist
would give you the same result but then you may want to check if $_POST['tags']
is an array...
$tags = isset($_POST['tags']) ? implode(", ", noescape($_POST['tags'])) : null;
or
$tags = (isset($_POST['tags']) && is_array($_POST['tags'])) ? implode(", ", noescape($_POST['tags'])) : null;
You can test here : http://codepad.org/XoU4AdsJ
OTHER TIPS
That should work:
if (isset($_POST['tags']) && is_array($_POST['tags'])){
$tags = implode(", ", noescape($_POST['tags']));
}
if(array_key_exists('tags',$_POST))
{
..................
}
if (!empty($_POST['tags'])) {
$tags = implode(", ", noescape($_POST['tags']));
}
I would just use is_array before imploding so your implode only works if your imploded var is an existing array. Returns 0 if it is not set as well :)
Actually, an easier way to do this would be to do something like this:
<input type="hidden" name="tags[]" value="none" />
<input type="checkbox" name="tags[]" value="Tag 1" />
<input type="checkbox" name="tags[]" value="Tag 2" />
<input type="checkbox" name="tags[]" value="Tag 3" />
And then remove the default value.
Obviously this would still cause errors if some malicious user decided to send a post to your script without any data at all.
I'd use is_array() and count():
if (is_array($_POST['tags']) && count($_POST['tags'])>0){
$tags = implode(", ", noescape($_POST['tags']));
}