0

Consider the following example:

if ( isset($_POST['type']) && 'page' == $_POST['type'] )
    return;

Do we need the isset($_POST['type']) check?

From what I've seen so far the following has the seem result:

if ( 'page' == $_POST['type'] )
    return;

Or can this cause problems in certain situations?

  • 1
    If error_reporting is enabled and $_POST['type'] is not set than it generates undefined index warning. – Rakesh Sojitra Oct 05 '16 at 09:22
  • I always check with isset, after the isset I check with trim if it is null or not. – Koen Hollander Oct 05 '16 at 09:22
  • isset() and empty are the important functions of php .. issset() only checks the variable is not null but empty() checks if the variable is set and if it is it checks it for null, "", 0, etc.. using both function is a mature tatics for solving pblms .. please read php manual for more – anuraj Oct 05 '16 at 09:24
  • Yes I know it's good and also the reasons why, but in this particular case it doesn't seem do anything. Could there be a case where `if ( 'page' == $_POST['type'] )` would fail? Edit: Allready answered by @Rakesh Sojitra and @Anuraj P.R – projectIncomplete Oct 05 '16 at 09:25

2 Answers2

0

Using "isset" is right approach otherwise it will throw warning: "index type is undefined". Also it checks whether array is empty or not.

isset() function will serve the replacement of two functions

if(!empty(your_array) && array_key_exists('type',$POST['type']))

So use this check to avoid further complications

0

This can cause problems like error notice: PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"

You can use array_key_exists instead of isset. array_key_exists method will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null

There is another important difference.isset doesn't complain when $x does not exist, while array_key_exists does.

$x = [
    'key1' => 'abcd',
    'key2' =>  null
];

isset($x['key1']);             // true
array_key_exists('key1', $x);  // true

isset($x['key2']);             // false
array_key_exists('key2', $x);  // true
Community
  • 1
  • 1
Mateusz Palichleb
  • 765
  • 12
  • 20
  • Only using `array_key_exists` alone will not serve purpose. Yu have to apply one more check `empty` with it. Because array_key_exists will not check whether your array is empty or not. Once you pass on check `if(!empty(my_array)` then check for its key whether that array has key or not. – Sugandh Khanna Oct 05 '16 at 09:36