Steve F
Steve F

Reputation: 1567

array_key_exists not working correctly

Running: PHP 5.6.7 on Windows / Apache

The "array_key_exists" function is not returning the correct result, if the key being searched (needle) is the last element in the array being searched (haystack).

echo phpversion();  echo  "<br>";
var_dump($modulepriv_ass);  echo  "<br>";  var_dump($uploadpriv_ass);  echo  "<br>";

foreach($modulepriv_ass as $menuid) {
  $fileuppriv = 0;                           echo $menuid  ;
  if (array_key_exists($menuid, $uploadpriv_ass)){
    $fileuppriv = 1;                        echo  " T";
  }                                               echo  "<br>";

}

And this is the output being produced:

5.6.7
array(10) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" [5]=> string(1) "6" [6]=> string(1) "7" [7]=> string(1) "8" [8]=> string(1) "9" [9]=> string(2) "10" }
array(5) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" [3]=> string(1) "4" [4]=> string(1) "5" }
1 T
2 T
3 T
4 T
5
6
7
8
9
10

Clearly the key "5" should have a "T" next to it. Can anyone help?

Upvotes: 0

Views: 389

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

No, it shouldn't. array_key_exists checks for the existance of keys, not values. Your $uploadpriv_ass array's last key is 4, and you're passing the value of 5 to array_key_exists. Since $uploadpriv_ass[5] is not set, you're not getting the "T".

Upvotes: 2

Related Questions