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!

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


Help with PHP

Could someone help me with the code below. I only want it to echo out 'book1' or 'book2'. at the moment it echos out both statements, which is what i would expect it to do. I'm not such how to select each element out of the array. I tried $mode_allowed[0] but it gives me an error.


$mode_allowed = array('book1', 'book2');

if (isset($_GET['book']) === true && in_array($_GET['book'] , $mode_allowed) === true){ $errors[] = 'Book 1'; }

if (isset($_GET['book']) === true && in_array($_GET['book'] , $mode_allowed) === true){ $errors[] = 'Book 2';

} else $errors[] = 'opps, we cant find book';


<?php echo output_errors($errors); ?>

3 Answers

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

The in_array function lets you look for a specific value inside of an array. If it finds the value in the array, it returns true; if it doesn't, then it returns false. Right now, this is your conditional:

if (isset($_GET['book']) === true && in_array($_GET['book'] , $mode_allowed) === true)

This asks the question "Is the GET variable book set, and is its value in the $mode_allowed array?"

If you change it to this --

    if (isset($_GET['book']) === true && in_array($_GET['book'] , $mode_allowed[0]) === true)

-- it produces an error because $mode_allowed[0] is a string, not an array. You can only use in_array if the second argument is actually an array.

The smallest change would be this:

    if (isset($_GET['book']) === true && $_GET['book'] == $mode_allowed[0])

This asks the question "Is the GET variable book set and does it have the same value as the first element in the array?"

Though I'm not sure why you are using an array at all. If you are going to hard-code the value you assign to $errors within the conditional, why not hard-code the value checked in the conditional?

    if (isset($_GET['book']) === true && $_GET['book'] == 'book1')

Does that help?

Thanks Randy. I was using an array because I was trying to edit some code I already had. Thanks for taking the time to explain what I was doing wrong. It really helps rather then just being told the answer.