Array, 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?

Thank you.

[fphp]isset[/fphp] & [fphp]is_array[/fphp] should do the trick.

what error msg do you get?


<?php
error_reporting(-1);
ini_set('display_errors' ,true);


if(isset($_GET['tags']) && is_array($_GET['tags'])){
  printf(
    "SELECT id, title FROM post WHERE tag IN ('%s')",
    implode("','", $_GET['tags'])
  );
}

/**
 *  .php?tags[]=a&tags[]=b&tags[]=c&tags[]=d
 *  SELECT id, title FROM post WHERE tag IN ('a','b','c','d')
 */
?>

You do of course, need to properly sanitise the tags array. :slight_smile:

Thanks Anthony,

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

I personally don’t write code to avoid notices, because if you know what you’re doing they’re insignificant nagging and avoiding them requires you to clutter up the code with all kinds of unnecessary bloat. Take this for example:


if ( isset( $_POST[ 'tags' ] ) && is_array( $_POST[ 'tags' ] ) ) {

is_array() alone is sufficient for this purpose, because if $_POST[ ‘tags’ ] is not set, then it’s value will default to NULL and is_array() will return FALSE. If the var is set and is not an array, is_array() will return FALSE. Only if the var is set and is an array, then is_array() will return TRUE. In this case the only thing isset() accomplishes is avoiding a notice.