phparraysarray-key-exists

array_key_exists is not working well


I have this array:

$variableNames = [
        'x1',
        'x2',
        'x3',
        'x4',
        'x5',
        'x6',
        'x7'
    ];

But, when i use array_key_exists function like this:

array_key_exists('x3', $this->variableNames)

It return false. But, if i have this array:

$variableNames = [
        'x1' => null,
        'x2' => null,
        'x3' => null,
        'x4' => null,
        'x5' => null,
        'x6' => null,
        'x7' => null
    ];

It return true. How can i use the first array, and get true? In the first array, the value is null also, like the second array. So, why the first array return false and the second array return true?


Solution

  • array_key_exists() search for keys not values.

    In your first case, you x3 is in value.

    So, its not searching.

    In this case you can use in_array(), this function searches for values.

    In second case, x3 is key, therefore, searching properly.