In_array() always returns TRUE [duplicate]

Asked
Active3 hr before
Viewed126 times

6 Answers

duplicatearrayalwaysreturns
90%

Basically here 0 treats as false, so the search will occur like the function in_array search false between your array value. Make it(0) string to get different output. As php a support strict or non-strict comparison so you need to pass a third value true it tell the to be strict because by default it is non-strict., 3 See the first comment here: nl1.php.net/in_array Add a third parameter true in the in_array function to set the checking to strict. – KrekkieD May 19 '14 at 10:46 , Are there any gaps in the range of gravitational wave frequencies we can detect? , You pretty much have to use strict equality with in_array, is the conclusion I've come to, or you'll have situation like this: echo in_array('test',['fail' => true]) ? 'WHOOPS' : '' – 111 Jan 14 '20 at 5:37

That's because the function uses a non-strict comparison. The string in the array is compared to integer 0. Some typecasting is happening with data loss, and both are regarded the same:

var_dump(0 == 'first'); //  bool(true)
load more v
88%

Why in_array() matches needle 0 to any given haystack?,Docs: http://nl3.php.net/in_array,Basically here 0 treats as false, so the search will occur like the function in_array search false between your array value. Make it(0) string to get different output. As php a support strict or non-strict comparison so you need to pass a third value true it tell the to be strict because by default it is non-strict.

$arrValue = array('first', 'second');
$ret = in_array(0, $arrValue);
var_dump($ret);
var_dump($arrValue);

Above example gives following result:

bool(true)
array(2) {
   [0] => string(5)
   "first" [1] => string(6)
   "second"
}
load more v
72%

I am trying to take all the information from $results and input it into a text file, sometimes we get duplicates in $results so I want to check the text file for the entry before writing it in so we don't get duplicates in the text file. However inarray keeps returning false, even when I echo out the two arrays and they match?,$results['info'] is loaded from a fetch to an API. The problem with processing it before hand is the API we are dealing with only allows 10 results at a time, so we loop it several hundred times to get the data out.,ok, that definitely helped. However I am still getting duplicates in the text file. It seems to allow one duplicate before it starts detecting them. There must be an error in my loops somewhere?, The code below works, however it doesn't seem to catch duplicates until their is already one. If I feed the exact same data into it, say 6 times. It'll insert it into the text file twice, then start reading the duplicates and skipping them. I need to get it so it's only inserting the same data in once and not twice.

$myfile = "complete.txt";

foreach($results['info'] as $data) {

   $output = $fields['firstname'].
   "|".$record['lastname'].
   "|".$record['address'].
   "|".$record['number'].
   "\n";

   $handle = fopen($myfile, "r");
   $contents = fread($handle, filesize($myfile));
   fclose($handle);

   $list = array();

   $list = explode("\n", $contents);
   $list = array_map("trim", $list);

   $current = $output;

   echo in_array($current, $list) ? $current.
   ' exists': $current.
   ' does not exist';

   if (in_array($current, $list)) {
      print "duplicate";
   } else {

      if ($file = fopen($myfile, "a")) { //open file for writing
         fwrite($file, $output); //write to file
      }

   }

}
load more v
65%

So an empty string or array will evaluate to false and non empty strings or arrays will evaluate to true.,On the other hand isset() will determine if a variable is defined regardless of it's actual value. The only value being somehow different is null. A variable with value null will return false if tested with isset().,So solve this, you can use the third parameter and set it to true to request strict comparison.,Keep in mind, through, that strict is really strict. In a strict comparison, 0 is not equal to "0".

$arrValue = array('first', 'second');
$ret = in_array(0, $arrValue);
var_dump($ret);
var_dump($arrValue);

Above example gives following result:

bool(true)
array(2) {
   [0] => string(5)
   "first" [1] => string(6)
   "second"
}
load more v
75%

Takes an input array and returns a new array without duplicate values. ,Note: Note that array_unique() is not intended to work on multi dimensional arrays. ,array_unique — Removes duplicate values from an array,array_count_values() - Counts all the values of an array

Array
   (
      [a] => green[0] => red[1] => blue
   )
load more v
40%

It turns out that PHP in_array will always return true for a string type "needle" if ANY value in the array is 0.,in_array('uid', [ 'a', 'b', 0 ]) == true,I had to add a "true" for the strict setting to in_array to fix the issue.,I have an issue where the SAML payload has an attribute that actually has the name of "0". I have no control over what is in the payload. I don't care about this particular attribute at all BUT because of how the code is working in Saml2/Response.php it's causing breaking issues.

            if (in_array($attributeKeyName, array_keys($attributes), true)) {
               if (!$allowRepeatAttributeName) {
                  throw new ValidationError(
                     "Found an Attribute element with duplicated ".$keyName,
                     ValidationError::DUPLICATED_ATTRIBUTE_NAME_FOUND
                  );
               }
            }
load more v

Other "duplicate-array" queries related to "In_array() always returns TRUE [duplicate]"