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);
}
1
  • If this foreach is outside of $query_item (which I presume so as your not using $this) are the properties public or otherwise accessible? Commented Apr 9, 2010 at 15:35

2 Answers 2

3

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 &.

Sign up to request clarification or add additional context in comments.

6 Comments

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?
Modifying by Reference is smart. But the second example isn't $query_item an array? $query_item[$key] = ... ?
No. He said: "I need to remove the '&' character from each property of a php object." An object is not an array, therefore you'd need to use ->$key. However, the first one would work best. Just remove the spaces, they're unnecessary and might mess up if someone uses something like this&that.
$query_item is an object your second method worked for me, thanks!
I should have been more clear, I actually do want to spaces around the ampersand, but thanks for lookin out for me
|
1
foreach($query_item as $key => &$value)
{
    $query_item[$key] = str_replace(' & ',' & ',$value);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.