![](/img/trans.png)
[英]“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.