array_map and htmlentities
Solution 1
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);
}
Solution 2
Use array_walk_recursive
. array_map
doesn't work with multidimensional arrays:
array_walk_recursive($lang, function (&$value) {
$value = htmlentities($value);
});
Solution 3
$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.
Solution 4
Each element in $lang is an array, so the function you pass to array_map should take an array as an argument. That is not the case for 'htmlentities' which takes a string.
You can:
$map_htmlentities = function(array) { return array_map('htmlentities', array); };
and then
$lang = array_map($map_htmlentities, $lang);
From PHP 7.4 on you can use lambdas:
$lang = array_map(fn($arr) => array_map('htmlentities', $arr), $lang);
Solution 5
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.
Fabian
Updated on June 27, 2022Comments
-
Fabian almost 2 years
I've been trying using
array_map
to convert characters to HTML entities withhtmlentities()
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!