Forum Moderators: coopster

Message Too Old, No Replies

Easier way to check if an array key exists and has a value

And is compliant with E_STRICT ¦ E_ALL

         

physics

5:05 am on Dec 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



In an attempt to try to develop cleaner PHP code I'm using

error_reporting(E_ALL);

Problem is with that I can't be lazy (yes I know that's the point) and do:


if($_SESSION['foo']){
...
}

Because that returns an error like:

Notice: Undefined index: loggedin in ... line 10

The following does the trick


if ( array_key_exits('foo',$_SESSION) and $_SESSION['foo'] ) {
...
}

but I'm wondering if there's a shorter way that won't generate an error. Anyone know of one?

<correction>I had blamed E_STRICT but it's actuall E_NOTICE that generates the Notice: error, oops...</correction>

mcavic

5:42 am on Dec 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if (isset($_SESSION['foo']))

I've found that that also executes faster than the equivalent array_key_exists call.

physics

5:52 am on Dec 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks mcavic, that seems to do the trick.