Manish Balodia
Manish Balodia

Reputation: 1877

Input type select return empty array in php validation

I have using following function for clean form data.

function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return htmlspecialchars($str);          
}

It gives empty array of the following field.

$value = clean($_POST['tags_id'];

and after removing clean() function, it give all selected value(means no empty array)

<select name="tags_id[]" multiple="multiple" data-rel="chosen" style="width: 220px">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>

Upvotes: 0

Views: 1054

Answers (2)

Krishna38
Krishna38

Reputation: 735

You can try like this

if (isset($_POST['submit'])) {
  foreach($_POST['tags_id'] as $key => $val) {
    echo "val".clean($val); // Here you will get clean values
  }
}

function clean($str) {
  $str = @trim($str);

  if (get_magic_quotes_gpc()) {
    $str = stripslashes($str);
  }
  return htmlspecialchars($str);
} 

Upvotes: 4

jeroen
jeroen

Reputation: 91734

If you look at your form:

<select name="tags_id[]" multiple=...
                     ^^ here

You will see that tags_id is an array, so $_POST['tags_id'] is an array.

You cannot use string functions on your array, you would have to loop over the elements of the array and call your clean() function on those. See here what happens when you use trim() on an array: example.

You can also check in your function if the value is an array and handle it accordingly.

Upvotes: 1

Related Questions