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 trial

PHP Enhancing a Simple PHP Application Adding Search: Model Using stripos: Starts with R

struck on this CC

I have this block of code that isn’t working correctly, but I can’t figure out the problem. It says that Broccoli and Cream Soda both start with R (my favorite letter), but they do not. Can you take a look? Can you change it so that it checks that the values in $var1 and $var2 start with R correctly?

<?php

$var1 = "Broccoli";
$var2 = "Cream Soda";
$initial = "R";

if (stripos($var1,$initial) == 1 && stripos($var2,$initial) == 1) {

  echo $var1 . " both start with " . $initial . ".";

} else {

    echo   $var2 . " doesn't start with " . $initial . " ; maybe neither of them do.";

}

?>

4 Answers

Andrew Shook
Andrew Shook
31,709 Points

In PHP, and most modern programming languages like Java, JavaScript, Python, and Ruby, you should think of strings as an arrays of letters. This is a through back to the C programming language, which most of these languages mimic. So like arrays, all strings are zero indexed. Thing means the numeric value of the first position is 0 and not 1. The reason this code is giving a false positive is because the if statement is check the second letter not the first. Here is a visual :

"Broccoli" = ["B", "r", "o", "c", "c", "o", "l", "i"];
              0     1    2    3    4    5    6   7

"Cream Soda"  = ["C", "r", "e", "a", "m", " ",  "S", "o", "d", "a"]
                  0    1    2    3    4    5     6    7    8    9

So in the if statement it is asking if the position of "R" in either word is 1 position from the start of the word, or the second letter. However, what its suppose to be checking is whether the first letter, or the "0" position from the start of the word, is "R". Hope this helps.

Just change the ones to zeros in: if (stripos($var1,$initial) == 1 && stripos($var2,$initial) == 1) {

hi yaso can u show me the full copy of the answer

if (stripos($var1,$initial) == 0 && stripos($var2,$initial) == 0) {

JUST CHANGE ONES TO ZEROS