1

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?

0

7 Answers 7

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
3

Try like

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

or you can use search(optional) like

if(array_search('0',$process)) {

2 Comments

+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.
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.
2

I believe you should put 0 inside the quotes:

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

Comments

1

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

 if (0 == "deleted") echo "xx";

Comments

1

Try this

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

Comments

1

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"

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.