0

So, I am working on a little project in PHP and when I go check my webpage I see these two errors:

Notice: Undefined index: has_char in C:\xampp\htdocs\characters.php on line 35

Notice: Undefined index: has_char in C:\xampp\htdocs\characters.php on line 42

I cannot seem to figure out how to check the $_SESSION['has_char'] to see if it is true or false, because depending on that the user would see something different on the webpage. I tried to do it my way and I got those two errors, how would I correct this and make it work?

<!DOCTYPE html>
<html>
<head>
    <title>Character Screen</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>

<div class="header">
    <h2>Character</h2>
</div>
<div class="content">
    <?php
    echo "Welcome," . " ". $_SESSION['username'] . "!";
    ?>
    <?php if($_SESSION['has_char'] === False) : ?>
            <div class="no character">
            <?php echo "You do not have a character." ?>
            Click <a href="charactercreation.php">here</a> to make one!
        </div>
    <?php endif ?>
    <?php
        if($_SESSION['has_char'] === True) {
            echo("Your character is". $char_name);
        }

    ?>
</div>
<div class="log out">
    <br>
    <a href="logout.php">Log Out</a>
</div>

</body>
</html>

"if($_SESSION['has_char'] === False" and "if($_SESSION['has_char'] === True" seem to be the troublemakers, but I lack a good solution to this.

JIJOMON K.A
  • 1,290
  • 3
  • 12
  • 29

1 Answers1

3

One way is to use isset()

if ( isset($_SESSION['has_char']) && $_SESSION['has_char'] === True) {
    echo("Your character is". $char_name);
}

You can also set a default value so that you know there is a value.

$hasChar = $_SESSION['has_char'] ?? null;
if ( $hasChar === true ) {
    // something is true
} elseif ( $hasChar === false ) {
    // something is false
} else {
    // something is null
}

And then there is array_key_exists()

if ( array_key_exists('has_char', $_SESSION) && $_SESSION['has_char'] === true ) {
    // something is true
}
ryantxr
  • 4,119
  • 1
  • 11
  • 25