How to loop through php object and replace string in each property (variable)

I need to remove these "and" characters from every property of php object

I tried the code below but it doesn't work ... what am I missing?

thanks dudes

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

      

+2


source to share


2 answers


You have to reference the $ value by reference and change it in place:

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

      

An alternative would be to reference an element within an object using the $ key:



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

      

I'll also specify htmlentities () , while we're going to replace and with amp ;.

+4


source


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

      



+1


source







All Articles