If the array is isset, do something?

I place several flags and put them in an array - for example: "tags []"

When you send them, I will tarnish them with commas.

If NO tags are tagged on the form and then submitted, I get errors because the script is trying to explode something that is not there.

I tried using something like this:

if (isset($_POST['tags'])){ $tags = implode(", ", noescape($_POST['tags'])); } 

What is the best way to check if it exists and then blow it up?

isset, array_key_exists?

+4
source share
7 answers

You can do this on one line, in this situation isset and array_key_exist will give you the same result, but then you can check if $_POST['tags'] 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

+6
source

This should work:

 if (isset($_POST['tags']) && is_array($_POST['tags'])){ $tags = implode(", ", noescape($_POST['tags'])); } 
+2
source
 if(array_key_exists('tags',$_POST)) { .................. } 
+2
source
 if (!empty($_POST['tags'])) { $tags = implode(", ", noescape($_POST['tags'])); } 
+1
source

I would just use is_array before detonating, so that your implode works only if your exploded var is an existing array. Returns 0 if it is also not installed :)

http://php.net/manual/en/function.is-array.php

+1
source

I would use is_array () and count ():

 if (is_array($_POST['tags']) && count($_POST['tags'])>0){ $tags = implode(", ", noescape($_POST['tags'])); } 
+1
source

In fact, an easier way to do this is 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 will still cause errors if any malicious user decides to send a message to your script without any data whatsoever.

+1
source

All Articles