I'm trying to keep duplicate items from being inserted into an array and am using array_search to check if the item already exists. I'm having problems understanding why this doesn't work:

$niins_array = array('6240001433165' => 1, '1005014660310' => 2 );

$niin = '1005014660310';

if(!array_search($niin, $niins_array)) {
 echo 'y';
} else {
  echo 'n';
}

It still prints 'y' even though the item is in the array. Am I missing something here?

    Oh, heck, nevermind, I should be using array_key_exists() instead...

      php.net wrote:

      array_search — Searches the array for a given value and returns the corresponding key if successful

      You were searching for keys.
      Also, you code was wrong:

      if(!array_search($niin, $niins_array)) {
      echo 'y';
      } else {
        echo 'n';
      } 
      
      // this says: "If value NOT in array, print "y[es, in array]", else print "n[ot in array]"
      // didn't you want the other way around?

      One last thing. When a functions returns 0 (a possible array key), a conditional interprets this as FALSE. You must use strict comparison (===, or !==).

      <?php
      
      // this was the correct case
      $niins_array = array(1 => '6240001433165', 2 => '1005014660310');
      
      $niin = '1005014660310';
      
      if (array_search($niin, $niins_array)) {
          echo 'y<br />';
      } else {
          echo 'n<br />';
      }
      
      
      $arr = array(1, 2, 3, 4, 5, 6);
      
      // this echoes "Value not found", although value '1' is present
      echo (!array_search('1', $arr)) ? "Value not found<br />" : "Value found<br />";
      
      // the correct way is this:
      echo (array_search('1', $arr) !== FALSE) ? "Value found<br />" : "Value not found<br />";

      More on comparison @php.net.

      Now I see that, when using, for example, $arr = array(1 => 1, 2, 3, 4, 5, 6), you code works without strict comparison.
      Also, now I see even more - you number of posts. 😃 I guess you knew all of this, but maybe will help some other newbie.

        Write a Reply...