5

So I have this foreach loop - and I want to modify the array based on my modification of the values. However when I try to later convert $bizaddarray to a string, all of the HTML tags are still present. Here's my foreach loop - how can I make the strip tags permanent?

    foreach ($bizaddarray as $value) {
        strip_tags(ucwords(strtolower($value)));
    }
Steven Matthews
  • 9,705
  • 45
  • 126
  • 232

2 Answers2

9

Two ways, you can alter the memory location shared by the current value directly, or access the value using the source array.

// Memory reference
foreach ($bizaddarray as &$value) {
    $value = strip_tags(ucwords(strtolower($value)));
}
unset($value); # remove the reference

Or

// Use source array
foreach ($bizaddarray as $key => $value) {
    $bizaddarray[$key] = strip_tags(ucwords(strtolower($value)));
}
Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
  • 2
    I'd recommend doing option 2 but with a copied array as I don't think PHP deals nicely with you changing keys of the array it's iterating over. Fine in this instance but not best practice in general. and I seem to remember option 1 giving me hell a few times because PHP not resetting the pointers after the foreach was finished and getting some ghost changes. messy. – Paystey Oct 11 '11 at 22:35
  • Agree with Paystey. Option 1 should be avoided. If code doesn't immediately `unset($value);` any write to `$value` downcode will result in last array element being overwritten! – webbiedave Oct 11 '11 at 22:59
  • what about `foreach (array_keys($bizaddarray) as $key) { $bizaddarray[$key] = strip_tags(ucwords(strtolower($bizaddarray[$key]))); }` – Capi Etheriel Jun 17 '12 at 06:32
0
foreach ($bizaddarray as $key => $value) {
    $bizaddarray[$key] = ucwords(strtolower($value));
}
Logan Serman
  • 29,447
  • 27
  • 102
  • 141