-1

I accidentally experience this issue when I was writing code in one of my application.

$ar = [
   'first' => 1,
   'second' => 2,
   ......
]; 

when I tried to check that index in $array which doesn't exist

if(isset($ar['third']) && !empty($ar['third'])){
    echo "Found";
}else{
    echo "Not Found";
}

It worked without error as expected, but when I put this conditions in the common function and then checked

function sanitize($value){
   if(isset($value) && !empty($value)){
       return true;
   }else{
       return false;
   }
}

if(sanitize($ar['third'])){
   echo "Found";
}else{
   echo "Not Found";
}

Above sample throws an exception undefined index error, can someone explain why this is causing the error.

John Conde
  • 217,595
  • 99
  • 455
  • 496
Aman Maurya
  • 1,305
  • 12
  • 26
  • This said, this question is a simple typo. – Mike Doe Oct 09 '18 at 12:23
  • 1. `sanitize` is a bad name for this function, since it doesn't "sanitise" anything. Just saying, hope it's just an example. 2. `isset && !empty` is redundant. 3. If `$ar['third']` doesn't exist here: `sanitize($ar['third'])`, you can't have any expectation that code *inside* the function will suppress that error. – deceze Oct 09 '18 at 12:29
  • [The Definitive Guide To PHP's isset And empty](http://kunststube.net/isset/) – deceze Oct 09 '18 at 12:30
  • @deceze yes it's just an example – Aman Maurya Oct 09 '18 at 12:31
  • 3
    The key thing to remember is that `isset` is not a function, but a special language construct. Since its purpose is to detect variables, array elements, or object properties which are uninitialized, it bypasses the normal check that would raise a Notice. But in your code, the Notice *was already raised* before the `isset` line is reached, so it's too late for it to suppress the check. – IMSoP Oct 09 '18 at 12:31

2 Answers2

1

$value is always set because it is declared as a function parameter so it always exists. So in this case using isset() is pointless.

function sanitize($value){ // <-- Variable is declared so it exists 
                           // within the scope of this function
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

You are trying to refer to the $ar array at that the 'third' index before the isset/empty check is actually executed (as that is within the sanitise function).

PHP is therefore showing the error for the if(sanitize($ar['third'])){ line.

psx
  • 4,040
  • 6
  • 30
  • 59