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 Browser Persistent Data with PHP Data Persistence on the Web Checking for Sessions

Robert Cooper
Robert Cooper
22,704 Points

Unable to verify if string is empty using trim function

I keep getting an error on the second part of the code challenge and I can't figure out why. I'm using an "OR" operator to also check if the value for the string is empty, but my answer is not being accepted. Any help would be appreciated!

story.php
<?php
for ($i = 1; $i <= 5; $i++) {
  if ( !isset($_SESSION['word'][$i]) || trim($_SESSION['word'][$i]) == false) {
    header('location: /play.php?p=' . $i);
    exit;
  }
}
story.php
<?php
session_start();

for ($i = 1; $i <= 5; $i++) {
  if ( !isset($_SESSION['word'][$i]) || trim($_SESSION['word'][$i]) == false) {
    header('location: /play.php?p=' . $i);
    exit;
  }
}

$word1 = htmlspecialchars($_SESSION['word'][1]);
$word2 = htmlspecialchars($_SESSION['word'][2]);
$word3 = htmlspecialchars($_SESSION['word'][3]);
$word4 = htmlspecialchars($_SESSION['word'][4]);
$word5 = htmlspecialchars($_SESSION['word'][5]);

include 'inc/header.php';

echo '<h1>My Treehouse Story</h1>';

echo '<p>There once was a(n) ' . $word1;
echo ' programmer named ' . $word2; 
echo '. </p>';
echo '<p>This ' .  $word3; 
echo ' programmer used Treehouse to learn to ' . $word4;
echo ' the ' . $word5 . '.</p>';

echo ' <a class="btn btn-default btn-lg" href="#" role="button">Save Story</a>';
echo ' <a class="btn btn-default btn-lg" href="play.php" role="button">Play Again</a>';
echo ' <a class="btn btn-default btn-lg" href="index.php" role="button">Other Stories</a>';


include 'inc/footer.php';
Daniel LittleThunder
Daniel LittleThunder
6,975 Points

It's because you're using the || (or) operator and not the && (and) operator. I believe you want to check that both conditions of the argument are true and not just one or the other. Below is the code that worked for me:

for ($s = 1; $s <= 5; $s++) {
 if (empty($_SESSION['word'][$s]) && trim($_SESSION['word'][$s] == FALSE)) {
   header("location:story.php?p=$s");
   exit;
 }
}

I think that it would also work with the NULL and the integer 0 in place of the FALSE keyword would also work, since they would evaluate to bool(false) as well, but I don't know enough about the difference in this particular case to know if one of these options is better than the others.