Burndog
Burndog

Reputation: 719

Why does this return an "Undefined Index" error?

The following code produces an Undefined Index error:

if(isset($_SESSION['sessionName'])); { echo $_SESSION['sessionName']; } 

But this works perfectly fine:

if(isset($_SESSION['sessionName'])) echo $_SESSION['sessionName']; 

Both check to see IF there is a $_SESSION set, then if TRUE show/echo that $_SESSION value. I generally use curly braces but do not see or understand the error in the first case. My IDE (PHPStorm) does not complain on syntax, so I am lost on what could be the problem.

Upvotes: 2

Views: 89

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74216

I converted my comment to an answer with additional information.

The semi-colon ends a statement, per the manual: "As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present."

What is happening here is that the first line you showed us, produces an error because the isset() is cancelled out/halted because of the semi-colon, and then you are trying to echo a session array that isn't set/not empty.

You also may not have started the session; that is unknown at the present time.

Upvotes: 2

Related Questions