2

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?

4 Answers4

6

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.

Pupil
  • 23,834
  • 6
  • 44
  • 66
2

The keys are not null, never.

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

means

$variableNames = [
        0 => 'x1',
        1 => 'x2',
        2 => 'x3',
        3 => 'x4',
        4 => 'x5',
        5 => 'x6',
        6 => 'x7'
    ];

use

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

instead.

KiwiJuicer
  • 1,952
  • 14
  • 28
0

Use in_array() instead of array_key_exists()

In your case,

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

if (in_array("x3", $this->variableNames)) {
    echo "Found x3";
}
6339
  • 475
  • 3
  • 16
0

No your incorrect. The function works well, you're just using it incorrectly. array_key_exists looks for the key, not value.

The first array you provided, is actually treated as a array of value. They have index keys, which are automatically added by PHP. I you print_r($variableNames), you'll see it will return the following.

$variableNames = [
        0 => 'x1',
        1 => 'x2',
        2 => 'x3',
        3 => 'x4',
        4 => 'x5',
        5 => 'x6',
        6 => 'x7'
    ];

You would need to search for the value instead. Use in_array() or isset(), both ways are right, one is just more convenient than the other.

André Ferraz
  • 1,511
  • 11
  • 29