Link to home
Start Free TrialLog in
Avatar of Colin Brazier
Colin BrazierFlag for United Kingdom of Great Britain and Northern Ireland

asked on

htmlspecialchars not working permanently on array values

I am trying to apply htmlspecialchars to data in a simple array.  The function "html" is set up to apply htmlspecialchars.

The data in the array seems to be unaffected after applying the function.

My debugging efforts are shown in the code.  The attached graphic is from view source.  So it seems to temporarily change Welling Town 'A' to Welling Town 'A' but when I print_r the whole array it has reverted to Welling Town 'A'

What am I missing here please?

echo("<pre>");
            print_r($arr_oppo);
			echo("</pre>");	
			
			if ($side == '4')
			{
				foreach ($arr_oppo AS $key=>$oppo_name)
				{
					echo "<br/>";
					echo "before: ".$oppo_name;
					echo "<br/>";
					$oppo_name = html($oppo_name);
					echo "after: ".$oppo_name;
					echo "<br/>";
				}	
			}
			
			echo("<pre>");
            print_r($arr_oppo);
			echo("</pre>");	

Open in new window

Capture.PNG
ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The first answer is the correct one.

Here is a bit more discussion on this issue.

The loop variable in a foreach loop is a value variable (copy) not a reference. That means whatever changes you make to it are not reflected in the original array.

One way to get around this is to use a reference variable in your loop

foreach ($arr_oppo AS $key => &$oppo_name) {
  ...
}

Open in new window

However this is not a great idea as it can have side effects. Unless you specifically unset $oppo_name - it will remain a reference to the last item of the array and so if used again in the code could result in unexpected results.
For instance
$data = ['a','b','c'];
foreach($data as &$d) {
   $d = strtoupper($d);
}

Open in new window

Result
Array
(
    [0] => A
    [1] => B
    [2] => C
)

Open in new window

Now do this
foreach($data as $d) {
   $d = $d . '_suffix';
}

Open in new window

Result
Array
(
    [0] => A
    [1] => B
    [2] => B_suffix_suffix
)

Open in new window

Because $d is still a reference to the last element of the array that is what is targeted.
Avatar of Colin Brazier

ASKER

Brilliant, thanks both.

Seems I need to do more reading on arrays.

Col
You are welcome.