tags:

views:

59

answers:

2

I need to remove these ' & ' characters from each property of a php object

I tried the code below but it's not working...what am I missing?

thanks dudes

foreach($query_item as $key => $value)
{
    $key = str_replace(' & ',' & ',$value);
}
+3  A: 

You should refer to $value by reference, and modify it in place:

foreach($query_item as $key => &$value)
{
    $value = str_replace(' & ',' & ',$value);
}

The alternative would be to reference the item within the object using $key:

foreach($query_item as $key => $value)
{
    $query_item->$key = str_replace(' & ',' & ',$value);
}

I'll also point out htmlentities(), while we're on the subject of replacing & with &.

Adam Backstrom
Just for my curiosity, the only difference in your first suggestion and mjr's original is that mjr was modifying $key whilst you are modifying $value. Is that the mistake?
JYelton
Modifying by Reference is smart. But the second example isn't $query_item an array? $query_item[$key] = ... ?
Ivo Sabev
Arda Xi
$query_item is an objectyour second method worked for me, thanks!
mjr
I should have been more clear, I actually do want to spaces around the ampersand, but thanks for lookin out for me
mjr
Adam Backstrom
@Adam, thanks I didn't see that! +1 by the way
JYelton
+1  A: 
foreach($query_item as $key => &$value)
{
    $query_item[$key] = str_replace(' & ',' & ',$value);
}
Ivo Sabev