Problem with array_key_exists

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
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Problem with array_key_exists

Post by Benjamin »

I have been passing values to a function which checks whether or not a key exists in an array. Everything worked fine until I starting using keys with letters. Here is an example of the array:

Code: Select all

Array
(
    [0] =>  
    [a] => blah
    [b] => blah
    [c] => blah
)
The code that checks is:

Code: Select all

function check_key($Key, $Array) {
    if (array_key_exists($Key, $Array)) {
      return true;
    } else {
      return false;
    }
}
duk
Forum Contributor
Posts: 199
Joined: Wed May 19, 2004 8:45 am
Location: London

Post by duk »

try to:

Code: Select all

function check_key($Key, $Array) {
    if (array_key_exists("$Key", $Array)) {
      return true;
    } else {
      return false;
    }
}
when you work with letters should be strings and not integers as when you work with just numbers...
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post by Ree »

You cannot use

Code: Select all

$arr[key] = 'string'
unless you have key defined as a constant. Use

Code: Select all

$arr['key'] = 'string'
instead.

Also, what exactly is the point of having a wrapper function for the native PHP one? It doesn't seem to do anything in itself right now.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

I can't show what it does as it's proprietary but there is a lot more to it then that.

The problem was this line above it:

Code: Select all

if ($Key === 0) { unset($Key); }
It was evaluating as true until I added 3 equal signs to it. I only had 2 on it before.
Post Reply