Undefined Index

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Pyrite
Forum Regular
Posts: 769
Joined: Tue Sep 23, 2003 11:07 pm
Location: The Republic of Texas
Contact:

Undefined Index

Post by Pyrite »

Why does:

Code: Select all

$foo = $_POSTї"bar"];
Return an Undefined Index if bar doesn't not exist (yet). How can I write my scripts to not have to deal with this issue?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$foo = (isset($_POSTї'bar']) ? $_POSTї'bar'] : 'default value');
smpdawg posted a function for this in the last day..
User avatar
Pyrite
Forum Regular
Posts: 769
Joined: Tue Sep 23, 2003 11:07 pm
Location: The Republic of Texas
Contact:

Post by Pyrite »

But why does it happen? Why even issue a notice saying that an array is yet to be created, yet it still works anyways. That is just dumb.

In my case, I often use it in a switch. And hae a default: in the switch in case it isn't defined yet. Unless I turn Notices off in error_reporting, this is bad for me. sucks.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

They get a default value of NULL when the index is undefined. It's typically not a big issue using an undefined value, but it is good to know that you are using one in case you have a bug related to it..
Post Reply