Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am facing one strange situation while working with PHP's in_array(). Below is my code and its output

<?php
$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
if(!in_array(0, $process))
    echo "success";
else
    echo "not success";

//It's outputting "not success";

var_dump(in_array(0, $process));
//Output : null

var_dump(in_array(0, $this->tProcessActions) === true);
///Output : true

If we look at the $process array, there is no 0 value in it. Still it's giving me true if I check if(in_array(0, $process))

Can anybody has idea about it?

share|improve this question
1  
0 == "deleted". –  cbuckley Jun 21 '13 at 10:06

7 Answers 7

up vote 3 down vote accepted

If you need strict checks, use the $strict option:

in_array(0, $process, true)

PHP's string ⟷ int comparison is well known to be complicated if you don't know the rules/expect the wrong thing.

share|improve this answer
    
+1 from me too. –  NullPointer Jun 21 '13 at 10:10
    
By putting true last parameter solved an issue. I seen it before long time and forgot to add when there is a mixed values in array like you said string-int –  NullPointer Jun 21 '13 at 10:11

Try like

if(!in_array('0', $process)) {

or you can use search(optional) like

if(array_search('0',$process)) {
share|improve this answer
    
+1 from me. Yes. You're right. But why I need to put 0 in Quotes? If I search for 1 without Quotes then it's giving correct result. –  NullPointer Jun 21 '13 at 10:07
2  
Because 0 == "deleted" using loose comparison. Note the third parameter to in_array, which forces strict comparison. Also have a look at the type comparison tables. –  cbuckley Jun 21 '13 at 10:07

I believe you should put 0 inside the quotes:

if(!in_array("0", $process))

share|improve this answer

I think because in_array maybe not strict type check. because if you check

 if (0 == "deleted") echo "xx";
share|improve this answer

Try this

if(!in_array('0', $process))
share|improve this answer

using the strict parameter gives what you want here:

$process = array("as12"=>"deleted","as13"=>1,"as14"=>1);
var_dump( in_array(0, $process, true ) );
// gives false

or use array_search and test if non-false;

var key = array_search( 0, array( 'foo' => 1, 'bar' => 0 ) );
// key is "bar"
share|improve this answer

You need use third parameter [$is_strict] of in_array function.

in_array(0, $process, true)

The point is what any string after (int) conversion equal to 0. (int) "deleted" => 0. So in_array without strict mode is equal to "deleted" == 0 which true. When you use strict its equal to "deleted" === 0 which false.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.