3

I'm trying to debug a script I wrote and there is an issue that comes down to checking if an identifier is present inside an (multidimensional) array of assets. I am using an in_array function that searches recursively that I got from this question.

Here is the function:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

I am using this data:

The needle: 'B51MM36'
The haystack: (apologies for the unbeautified array - couldn't find a way to beautify from var_export)

$sedols = array ( 0 => array ( 'ipsid' => '72', 'buyList' => '1', 'sedol' => 'B8LFDR7', 'isin' => 'LU0827876409', 'currency' => NULL, 'hedged' => '0', 'acc' => '0', 'inst' => '0', 'description' => 'BlackRock European Long Only', 'nonUKsitus' => '0', 'reportingStatus' => '0', 'matchScore' => 0, ), 1 => array ( 'ipsid' => '72', 'buyList' => '1', 'sedol' => 'LU0827876151', 'isin' => 'LU0827876151', 'currency' => 'USD', 'hedged' => '1', 'acc' => '1', 'inst' => '0', 'description' => 'Blackrock European Long Only', 'nonUKsitus' => '0', 'reportingStatus' => '0', 'matchScore' => 0, ), 2 => array ( 'ipsid' => '72', 'buyList' => '1', 'sedol' => 'LU0406496546 ', 'isin' => 'LU0406496546 ', 'currency' => 'EUR', 'hedged' => '1', 'acc' => '1', 'inst' => '0', 'description' => 'Blackrock European Long Only', 'nonUKsitus' => '0', 'reportingStatus' => '0', 'matchScore' => 0, ), 3 => array ( 'ipsid' => '72', 'buyList' => '1', 'sedol' => 'LU0827876409', 'isin' => 'LU0827876409', 'currency' => 'GBP', 'hedged' => '1', 'acc' => '0', 'inst' => '0', 'description' => 'Blackrock European Long Only', 'nonUKsitus' => '0', 'reportingStatus' => '1', 'matchScore' => 1, ), );

when I run var_dump(in_array_r('B51MM36', $sedols)); it outputs bool(true). I am confused as the string 'B51MM36' does not appear anywhere in the haystack array. Can anyone identify what is going on here?

Community
  • 1
  • 1
harryg
  • 20,382
  • 37
  • 112
  • 177

2 Answers2

2

The reson is that

var_dump('B51MM36' == 0);

is true, don't know why (maybe it convert the string to integer), but this work

var_dump(in_array_r('B51MM36', $sedols, true));

try remove strict option

jcubic
  • 51,975
  • 42
  • 183
  • 323
  • Yes that's it! It's casting the string to a boolean and/or integer which matches any 0 integer in the array. Enforcing strict is the way. Thanks – harryg Jul 04 '13 at 09:44
2

As has been mentioned by others, logic will not produce expected results. You must make suer the type matches as well. PHP does type juggling: http://php.net/manual/en/language.operators.comparison.php

So in this case 0=='B51MM36' will return true since value of B51MM36 is 0 after casting.

Hope this helps

tr33hous
  • 1,540
  • 1
  • 13
  • 26