简体   繁体   中英

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

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.

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 key s 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]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM