简体   繁体   中英

Applying htmlentities ENT_QUOTES on array

I have an array $fields:

Array
(
    [NAME] => M'y Na'me
)

I want to convert those apostrophes to entities. When I run:

array_map('htmlentities', &$fields, array_fill(0 , count($fields) , ENT_QUOTES) );

and then print_r $fields nothing seems to have changed?

Array
(
    [NAME] => M'y Na'me
)

How can I apply htmlentities with ENT_QUOTES on all elements in $fields ?

EDIT: this makes me lose my keys

$fields = array_map('htmlentities', $fields, array_fill(0 , count($fields) , ENT_QUOTES) );

According to the docs array_map returns a new array and doesn't modify the one passed in in-place.

$fields = array_map(
    'htmlentities', &$fields,
    array_fill(0 , count($fields) , ENT_QUOTES)
);

EDIT according to comment --

Since this is PHP, I suppose the best way is to forego the functional route and do it the old-school way:

foreach($fields as $key => $value) {
    $fields[$key] = htmlentities($value, ENT_QUOTES);
}

array_map does not modify the array, even if you pass it as reference.
Use $fields = array_map('htmlentities', $fields, ...) instead.

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