array_map and htmlentities

2020-07-23 03:54发布

I've been trying using array_map to convert characters to HTML entities with htmlentities() like this:

$lang = array_map('htmlentities', $lang);

My array looks like this:

$lang = array();
$lang['var_char1']['varchar2'] = 'Some Text';

But I keep getting this errors:

Warning: htmlentities() expects parameter 1 to be string, array given in /home/user/public_html/foo/lang/en.inc.php on line 1335

Does anyone know what could be the problem? Thank you!

5条回答
放我归山
2楼-- · 2020-07-23 04:21

array_map() doesn't work recursively. If you know your array is always two levels deep you could loop through it and use array_map on the sub-arrays.

查看更多
Luminary・发光体
3楼-- · 2020-07-23 04:32

if you like quotes


function stripslashes_array(&$arr) {
    array_walk_recursive($arr, function (&$val) {
        $val = htmlentities($val, ENT_QUOTES);
    });
}

multiple array in post, get, dll

stripslashes_array($_POST);

stripslashes_array($_GET);

stripslashes_array($_REQUEST);

stripslashes_array($_COOKIE);
查看更多
Rolldiameter
4楼-- · 2020-07-23 04:34

$lang['var_char1']['varchar2'] defines a multidimensional array, so each element of $lang is also an array. array_map() iterates through $lang, passing an array to htmlentities() instead of a string.

查看更多
【Aperson】
5楼-- · 2020-07-23 04:36

Use array_walk_recursive. array_map doesn't work with multidimensional arrays:

array_walk_recursive($lang, function (&$value) {
    $value = htmlentities($value);
});
查看更多
姐就是有狂的资本
6楼-- · 2020-07-23 04:42

Because $lang is a two dimensional array, so it won't work

For two dimensional array you need to use for loop

foreach($$lang as &$l):
    $l = array_map('htmlentities', $l);
}
查看更多
登录 后发表回答