-1

I have trouble understanding how the function array_keys works when I need it to return keys that have a certain value associated with it. For example, lets say we have an array like this:

$testArray = array
 (
    [key1] => value1,
    [key2] => value2,
    [key3] => 0
 )

My understanding of array_keys function tells me that calling this function on the given array like this:

array_keys($testArray,"value1")

should give this kind of response:

Array
(
    [0] => key1
)

But actually this is what I get:

Array
(
    [0] => key1
    [1] => key3
)

Which is strange, I think. Further testing revealed that this kind of thing happens always if I have number zero as a value in an array. It doesn't matter what value I search it for, it always returns the key that has zero as a value. Also, this happens only when the third parameter of array_keys, called strict, is set to false. If I set that parameter to true, the function works as I expect.

Am I missing something or is this an issue in PHP? I'm using PHP version 5.5.9.

DBWhite
  • 128
  • 2
  • 10

1 Answers1

2

When strings are compared, they are converted to numbers.

Try with -

array_keys($testArray,"value1", true);

Passing third parameter true will make it to compare with ===.

strict: Determines if strict comparison (===) should be used during the search.

array_keys

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87