Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If array isset, do something?

Tags:

arrays

php

isset

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?

like image 939
Latox Avatar asked Dec 09 '22 12:12

Latox


1 Answers

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

like image 79
Shikiryu Avatar answered Dec 12 '22 01:12

Shikiryu