PHP array and htmlentities

守給你的承諾、 提交于 2020-01-26 02:44:34

问题


$_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]);
    }
}
}

This is my code and what I was trying to do was that I wanted to split the $_POST array into $key and $val. Then I wanted to tell the program that as the $key goes up by 1, put htmlentities() around the $val. Can you please help me? I have been stuck on this for hours.


回答1:


You are doing this wrong way. Try with -

foreach($_POST as $key => $val){
    $_POST2[] = htmlentities([$val]);
}

No need for that for loop. foreach will wrap all the values. And if you want the keys to be same as $_POST then just leave it empty.




update 18.11.2019


In fact if you are dealing with a associative arrays such as _POST (as opposition to indexed arrays) where you are dealing with keys that have a name, and not with numbers, then you must write the code like this:

// this is the classic orthodox syntax 
foreach($_POST as $key => $val){
  $_POST[$key] = htmlentities($val);
}

If want to leave out the $key like suggested by my friend in the upper side it will work, but you will end up having a combined array that is associative AND indexed the same time (using double memory and tremendously slowing down your script). And what is more important it will not change the associative part, it will produce and append the indexed array that has been modified by 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);
}

If you work with indexed array you can always leave the $key out, but please also note that it is htmlentities($val) and not htmlentities([$val]).



来源:https://stackoverflow.com/questions/31870612/php-array-and-htmlentities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!