Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Object-Oriented PHP Basics Building a Collection Shopping List Method

strpos/ strstr confusion


I am confused as to why the browser doesn't display:

Egg Eggs Eggs

and instead only displays:

Egg Eggs

after the:

if (strpos($item, ",")) { $item = strstr($item, ",", true); }

statement is implemented. surely there should still be two'Eggs' in the display because there was both an Eggs and 'Eggs, Beaten' in the original shopping list and $item = strstr($item, "," , true) should still return 'Eggs' ( with the ", Beaten" removed). So why is there only one 'Eggs'? What happened to the other one?

Hope someone can help.

strpos — Find the position of the first occurrence of a substring in a string, in this case Eggs strstr - removes everything after the comma because of the value true. if (strpos($item, ",")) { $item = strstr($item, ",", true); } So there will only be one Eggs

3 Answers

My understanding is that it brings back the first instance of eggs and then doesn’t repeat any duplicates. Since the word beater was removed that would make the second eggs a duplicate

Hi Emma thanks for the answer, but I'm still confused. Although strpos does return only 'Eggs' there was already another item called Eggs (and a third item called Egg). I understand why Egg has disappeared but not Eggs. If there are any ideas I would be very grateful!!.

Thanks again

Great thanks Emma that makes sense :)