[英]“htmlentities() expects parameter 1 to be string, array given” in PHP
[英]PHP array and htmlentities
$_POST=
Array ( [0] => aaa@gmail.com [1] => bbb [2] => ccc [3] => ddd [4] => eee [5] => fff [6] => ggg [7] => hhh [8] => iii [9] => jjj [10] => 31 [11] => k )
foreach($_POST as $key => $val){
for ($key = 0; $key <= 9;$key++){
$_POST2[$val] = htmlentities($_POST[$val]);
}
}
}
这是我的代码,我想要做的是将$_POST
数组拆分为$key
和$val
。 然后我想告诉程序,当$key
增加1
,将htmlentities()
放在$val
周围。 你能帮我么? 我已经坚持了几个小时。
你这样做是错误的。 尝试 -
foreach($_POST as $key => $val){
$_POST2[] = htmlentities([$val]);
}
不需要那个for
循环。 foreach
将包装所有值。 如果您希望key
s 与$_POST
相同,则将其留空。
2019 年 11 月 18 日更新
事实上,如果您正在处理关联数组,例如 _POST(与索引数组相反),其中您正在处理具有名称而不是数字的键,那么您必须编写如下代码:
// this is the classic orthodox syntax
foreach($_POST as $key => $val){
$_POST[$key] = htmlentities($val);
}
如果想省去我朋友在上面建议的$key
,它会起作用,但是您最终将拥有一个关联并同时索引的组合数组(使用双倍内存并极大地减慢您的脚本速度)。 更重要的是它不会改变关联部分,它会生成并附加已被htmlentities
修改的索引数组。
// appends a indexed array
foreach($_POST as $key => $val){
$_POST[] = htmlentities($val);
}
// The & in front of $val permits me to modify the value of $val
// inside foreach, without appending a indexed array:
foreach($_POST as &$val){
$val = htmlentities($val);
}
如果您使用索引数组,您可以始终不使用$key
,但也请注意它是htmlentities($val)
而不是htmlentities([$val])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.