0

ik have a html form where i can select some options. I want to write those values comma separated to my database. This is the code i have

$genretotal = $_POST['genre'];
$genre0 = $genretotal[0];
$genre1 = $genretotal[1];
$genre2 = $genretotal[2];
$genre3 = $genretotal[3];
$genre4 = $genretotal[4];
$genre5 = $genretotal[5];
$genre6 = $genretotal[6];
$genre7 = $genretotal[7];
$genre = $genre0 . "," . $genre1 . "," . $genre2 . "," . $genre3 . "," . $genre4 . "," . $genre5 . "," . $genre6 . "," . $genre7;

How can i leave out the empty values?

2
  • 1
    why not do $genre = implode(',', array_filter($_POST['genre']));? Commented Aug 29, 2013 at 8:15
  • why not use like a foreach with a if statement or two Commented Aug 29, 2013 at 8:15

3 Answers 3

1

Try with implode and array_filter

implode(',', array_filter($_POST['genre']));
Sign up to request clarification or add additional context in comments.

1 Comment

Btw, this will filter out entries that evaluate to false, which includes '0' for instance. Using array_filter($_POST['genre'], 'strlen') may work better in those cases.
1

Why so?

$genre = join(',', array_filter($_POST['genre'], function($sItem)
{
   //here I assume your 'not empty' matches PHP empty() function
   //if not, then add desired conditions
   return !empty($sItem);
}));

Comments

0
$genretotal   =  $_POST['genre'];
if(isset($genretotal) && count($genretotal)>0)
{//This check array is null or not
    $gen_arr = implode(",",$genretotal);


}//end if
 echo $gen_arr;

//This is the code you avoid empty values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.