jim
jim

Reputation: 51

using empty does not provide correct results

Can someone please tell me why I'm able to echo inside of this block when the session clearly has a value?

$_SESSION['test']['testing'] = 'hgkjhg';
echo $_SESSION['test']['testing']; // Produces hgkjhg (Clearly not empty)

if(empty($_SESSION['test']['testing'])){
echo 'Hello'; // This echoes and to me, shouldn't
}

Upvotes: 5

Views: 87

Answers (3)

dragonjet
dragonjet

Reputation: 1006

The real answer is about session_start. Unlike session_register, assigning directly to $_SESSION does not automatically call session_start.

Directly from PHP manual for session_register()

If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made. $_SESSION does not mimic this behavior and requires session_start()

Upvotes: 1

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115530

Try changing it into:

$_SESSION['test']['testing'] = 'hgkjhg';
echo $_SESSION['test']['testing']; 

if(empty($_SESSION['test']['testing'])){
    echo 'Hello. Error in $_SESSION !'; 
}

If it is still echoing "Hello", then you have somewhere later in your code a line with:

echo 'Hello';

Upvotes: 0

Dawson
Dawson

Reputation: 7597

Try commenting out the rest of your code. Something is either hanging in the session, or you're assigning values elsewhere in your script.

<?php 
session_start();

$_SESSION['test']['testing'] = 'hgkjhg';
echo $_SESSION['test']['testing']; // Produces hgkjhg (Clearly not empty)

if(empty($_SESSION['test']['testing'])){
echo 'Hello'; // This echoes and to me, shouldn't
}

var_dump($_SESSION);
?>

Results:

hgkjhgarray(1) { ["test"]=> array(1) { ["testing"]=> string(6) "hgkjhg" } }

Just for argument's sake, you are saying you see "Hello" rather than "hgkjhg". "hgkjhg" should be displayed.

Upvotes: 0

Related Questions