2

I have some trouble with the result of in_array(). It is not like I would have expected and as I understand the manual.

Simple test:

$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0 , $_aOperatorsOneOptin);

if($bMatchPaymentOperator)
    echo 'found';

I would expect that I would get no result with this, but $bMatchPaymentOperator is true!

I would expect that

$bMatchPaymentOperator = in_array('DE-010' , $_aOperatorsOneOptin);

is true , which it is. But why oh why is the upper statement true?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Calamity Jane
  • 2,189
  • 5
  • 36
  • 68
  • Thank you for all the answers. I would not have thought that strict mode would be necessary here. I would have suspected it more in cases like 0== false. – Calamity Jane Jun 05 '15 at 08:10

5 Answers5

4

Use third parameter of in_array to force strict match

<?php

$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0 , $_aOperatorsOneOptin, true);

if($bMatchPaymentOperator == true)
    echo 'found';
Med
  • 2,035
  • 20
  • 31
3

This is because when you compare a number to a string in php, php converts the string to a number before doing the comparison. Strings that don't start with a number get converted to 0, so 0 == 'hello world';

You can force in_array to check the data type as well as the content for an exact match by passing true as the third argument to in_array().

$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0, $_aOperatorsOneOptin, true);

if($bMatchPaymentOperator)
    echo 'found';

see http://php.net/manual/en/language.operators.comparison.php for details on comparisons.

davey555
  • 720
  • 1
  • 7
  • 15
2

Because of PHP's truthy/falsy weirdness, I'd expect. Try:

$bMatchPaymentOperator = in_array('0' , $_aOperatorsOneOptin);
Kevin_Kinsey
  • 2,285
  • 1
  • 22
  • 23
2

It has to be in quotes:

$bMatchPaymentOperator = in_array('0' , $_aOperatorsOneOptin);
var_dump($bMatchPaymentOperator);

Result: bool(false)

RNK
  • 5,582
  • 11
  • 65
  • 133
1

The weird behavior is happening because 0 == "this is a string" i.e. 0 = any string in php just check this simple example

<?php
if( 0 == "this is a string"){
    echo("true");
}
else{
    echo("false");
}
?>

output : true

hence the in_array function shows such weird behavior

so as to make your code work just add strict parameter of in_array to true

check this code

<?php
$_aOperatorsOneOptin = array('DE-010', 'DE-005');

$bMatchPaymentOperator = in_array(0,$_aOperatorsOneOptin,true);

if($bMatchPaymentOperator){
    echo 'found';
}
else{
    echo "Not found";
}
?>

output: Not found

Akshay Khale
  • 8,151
  • 8
  • 50
  • 58