0

I have this program:

if (!isset($_POST['foo'])) doSomeThing1();
else {
    if (!array_key_exists('foo',$_POST)) doSomeThing2();
    else doSomeThing3();
}

but... the program flow goes to the 3d case, failing with the error: undefined index 'foo' (in file.php, line xxx).

Could you explain, why? Why array_key_exists returns true (which brings the script to the 3d case) but subsequently it is "undefined index"?

worldofjr
  • 3,868
  • 8
  • 37
  • 49

1 Answers1

1
if (!isset($_POST['foo'])) doSomeThing1();
else {
    if (!array_key_exists('foo',$_POST)) doSomeThing2();
    else doSomeThing3();
}

As per this code how it's working is...

!isset($_POST['foo']) ==> returns true and executes dosomeThing1() when there is NO 'foo' key in $_POST array

if $_POST doesn't have any key it is checking !array_key_exists('foo',$_POST)

array_key_exists('foo', $_POST) checking whether 'foo' key is there in $_POST array or not. array_key_exists('foo', $_POST) is same as isset($_POST['foo']) so it is always executing doSomeThing3() when there is no 'foo' key in $_POST array.

Hope this explanation helps.

YakovL
  • 7,557
  • 12
  • 62
  • 102