Search code examples
phparraysarray-pusharray-key-exists

How to properly use array_key_exists


$array = json_decode('[{"1234567":1368356071},{"7654321":1368356071}, etc, etc]');
$array2 = array(array(1234567 => time()), array(7654321 => time()));
   foreach($array2 as $key){
      if(!array_key_exists(key($key),$array))
           array_push($array, $key);
   }

Why are $keys that are in $array still getting pushed through to $array?

Pretty much I'm trying to prevent duplicate keys from getting pushed into $array..


Solution

  • Try This

    You had three problems

    1) You were decoding array into stdObject, it should be set true to return it to array

    2) You need to loop array as foreach($array2 as $key => $val)

    3) Pass as $array[0] in array_key_exists function

      $array = json_decode('[{"1234567":1368356071}]', true);
    
    $array2 = array(1234567 => time(), 7654321 => time());
    //echo count($array);
    foreach($array2 as $key => $val){
    
    
        if(!array_key_exists($key,$array[0]))
            array_push($array, $key);
    }
    echo count($array);