Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJonathan Grieve
Treehouse Moderator 91,253 PointsThis code outputs "1" to the screen. Why?
<?php
$flavors = array("Chocolate","Vanilla","Strawberry","Cookie Dough");
echo strpos( $flavors[strpos($flavors[3],"oo")], "a");
?>
This is a strpos that has 2 layers to it, it seems.
On the one hand,it seems to be searching for characters of oo and a
The oo one makes sense to me as the first instance of the o character appears in the 3rd index of strpos in the second character. so 1 would make sense.
But if $flavors[], is in it's own position, how do we know what position this is in?
Unless Vanilla counts as the second index and therefore is 1 and the a character is at position 1 in that element and therefore outputs as 1?
It's a tricky one. :)
1 Answer
Corey Cramer
9,453 PointsWhen evaluating the code it's easiest to work from the inside towards the outside so it would look like this:
<?php
// Original Code
$flavors = array("Chocolate","Vanilla","Strawberry","Cookie Dough");
echo strpos( $flavors[strpos($flavors[3],"oo")], "a");
?>
<?php
// Evaluate the interior strpos
$flavors = array("Chocolate","Vanilla","Strawberry","Cookie Dough");
echo strpos( $flavors[1], "a"); //$flavors[3] is "Cookie Dough" and "oo" appears as the first index since we always start at 0
?>