sgrontflix sgrontflix - 10 months ago 51
PHP Question

htmlentities() returns empty string when used with an array

When I use

to encode a variable it works like a charm, but if I do the same thing with an array it just returns an empty array. I tried to use
but it's the same story. I tried to switch the encoding to
but with no success. It doesn't want to work.

Here's the code:

<form name="signup" method="POST" action="form.php">
<legend><p style="color:red; font-size:16px">Sports</p></legend>
<input type="checkbox" name="sports[]" value="soccer">
<label for="soccer">Soccer</label>
<input type="checkbox" name="sports[]" value="water_polo">
<label for="water_polo">Water polo</label>
<input type="checkbox" name="sports[]" value="tennis">
<label for="tennis">Tennis</label>
<input type="checkbox" name="sports[]" value="volleyball">
<label for="volleyball">Volleyball</label>
$sports = htmlentities($_POST["sports"], ENT_COMPAT, 'ISO-8859-15');

$count = count($sports);
if($count == 0) {
echo "You don't play any sports.<br>";
} else {
echo "You like playing: ";
foreach($sports as $s) {
if(--$count == 0) {
echo "<span style='color:red'>$s</span>.<br>";
} else {
echo "<span style='color:red'>$s</span>, ";

It produces the following output:

You don't play any sports.

Meaning htmlentities() wasn't able to encode my array.

Answer Source

I'm not sure how you've tried using array_map, but the following is one correct approach:

function sanitize($arg) {
    if (is_array($arg)) {
        return array_map('sanitize', $arg);

    return htmlentities($arg, ENT_QUOTES, 'UTF-8');
$array = array_map('sanitize', $_POST);

This uses recursion so it will also work with multi-dimensional arrays.