Question

So I am trying to email the results of a form using PHP. inside my form I have a bunch of checkboxes. The script below works when at least 1 checkbox in a group is checked. If none of the checkboxes are checked I receive the following error:

Warning: Implode() [function.implode]: Invalid augments passed in {name of php doc} on line {xxx} Array

Here is a sample of the code I'm using:

 <?php
 $data = array();
   foreach ($_POST as $key => $value) {
      $data[] = $value;   
   }

 if(!$data[14]) //$data[14] is an array of checkbox values
    {echo 'No User Selection';}
 else
    {echo implode(" | ", $data[14]);} //This is where the error occurs 
 ?>

HTML code

 <label for="b0" class="left">Item 1</label>
 <input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
 <label for="b1" class="left">Item 2</label>
 <input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
 <label for="b2" class="left">Item 3</label>
 <input type="checkbox" name="b[2]" id="b2" value="Item 3"/>
 ect....

Does anyone have an idea why I'm receiving this error?

Était-ce utile?

La solution 2

If the checkbox is not checked, it is not sent to the server. I suggest you to do something like this:

<label for="b0" class="left">Item 1</label>
<input type="hidden" name="b[0]" value=""/>
<input type="checkbox" name="b[0]" id="b0" value="Item 1"/>
<label for="b1" class="left">Item 2</label>
<input type="hidden" name="b[1]" value=""/>
<input type="checkbox" name="b[1]" id="b1" value="Item 2"/>
<label for="b2" class="left">Item 3</label>
<input type="hidden" name="b[2]" value=""/>
<input type="checkbox" name="b[2]" id="b2" value="Item 3"/>

This way, you are sure that b[0], b[1], etc. are always sent

Autres conseils

Make sure the variable a) is set and b) is an array.

$data = array();
foreach ($_POST as $key => $value) {
    $data[] = $value;   
}

if ( !isset($data[14]) || !is_array($data[14]) ) {
     echo 'No User Selection';
} else {
    echo implode(" | ", $data[14]);
}

Always properly check variables using isset(), unless of course you like giant error logs! I also suggest using the $_POST keys as the keys for $data, thus making life even easier when you want to look up a specific $_POST item.

You are causing the problem yourself by making the data array. Just go straight to the POST array. Everything else is overcomplicating the problem.

<?php

     if(!isset ($_POST['b']) || !is_array($_POST['b'])) {
       echo 'No User Selection';
     } else {
       echo implode(" | ", $_POST['b']);
     }

?>

In addition, if the content of your form changes slightly, or you want to reorder the fields then your magic number 14 will no longer work.

Your code will be unbelievably fragile unless you change it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top