NYCPHP Meetup

NYPHP.org

[nycphp-talk] Escaping output in array isn't working

Dell Sala dell at sala.ca
Mon Jul 23 09:12:05 EDT 2007


On Jul 23, 2007, at 8:47 AM, Tim B wrote:

> # Escape for output into html
> foreach ($event as $v1)
> {
>    foreach ($v1 as $v2)
>    {
>       $v2 = htmlentities($v2, ENT_QUOTES, 'UTF-8');
>       echo "{$v2}<br>";
>    }
> }


The problem is that by default $v1 and $v2 are not *references* to  
the elements in the array you are looping through. Instead, they are  
copies of the values, so changing them doesn't have any effect on the  
original array. There are a couple ways around this:

1) if you're using php 5, you can make the value variable in the  
foreach statement a reference by prefixing it with "&":

foreach ($array as &$value) {
    $value = htmlentities($value);
}

2) or you can use the array keys to reassign the value back to the  
original place in the array:

foreach ($array as $key => $value) {
    $array[$key] = htmlentities($value);
}

As Cliff said, you can find the full details here:
http://us.php.net/foreach
http://us.php.net/manual/en/language.references.php

-- Dell





More information about the talk mailing list