0

I've got a problem which I can't seem to find a solution to. In a foreach loop

foreach( $results->result as $item )

the following code

$item->title = str_replace( " - Home", "", $item->title );

always throws an error

Catchable fatal error: Object of class stdClass could not be converted to string

I thought str_replace was able to handle arrays? What would I need to change in order to get this working?

Thanks for any advice!

2
  • It can handle arrays, but in your case $item->title is an object. Commented Oct 22, 2011 at 13:49
  • Thank you all for your amazingly quick help! :) Commented Oct 22, 2011 at 14:03

3 Answers 3

4

It's not an array, it's an object, as the error says... did you get it with json_decode() by any chance?

However, the solution is simple - cast it to an array:

$item->title = str_replace( " - Home", "", (array) $item->title );

Another point about this is that if you are wanting to modify the data held in $results->result, and not just a copy of it, you will need your foreach to be:

foreach( $results->result as &$item )

...and get item as a reference, not a copy...

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

Comments

2

$item->title seems to be an object of type stdClass, and not a string. Do var_dump($item->title) to see what the object looks like.

Also, you loop won't do what you expect, after the loop has finished, all objects in $results->result will still have the same values (use foreach($results->result as &$item) (pass by reference))

Comments

2

Do a var_dump on $item->title, because it isn't an array, it is an object. str_replace can only handle actual arrays and strings. If you're expecting this to be an array, then you might have some problems elsewhere and I would look into that.

If you're just looking for a patch, you might be able to get away with casting it. If everything else is working, I would do this because it really has the fewest side-effects:

// convert it to an array before passing it through str_replace
// (array) $item->title
// then convert it back to its original form by casting the result back
// (object) str_replace
$item->title = (object) str_replace( " - Home", "", (array) $item->title );

If title has to be an array, you can get away without the (object), but I think it would be a better idea to track down where title is being set and have the value correct to begin with.


BTW — if you're planning on using $item->title outside of the loop, you also need to make sure you are using a reference so that the item itself is updated:

foreach($results->result as &$item)
{
     $item->title = (object) str_replace( " - Home", "", (array) $item->title );
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.