Question

$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..

Was it helpful?

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);

OTHER TIPS

Because $array is 2 dimensional array and $array2 is 1D array, use below code

<?php

$array = json_decode('[{"1234567":1368356071}]',true);
print_r($array);
$array2 = array(array(1234567 => time()), array(7654321 => time()));
echo count($array);
foreach($array2 as $key){    

  if(!array_key_exists($key[0],$array[0]))
       array_push($array, $key);
}
echo count($array);

?>

Output

1
2

Codepad

The keyword isset works faster than the function array_key_exists.
You should use isset if you don't have to tell Undefined from NULL.

array_key_exists:

array_key_exists($key,$array);

isset:

isset($array[$key]);

Tested on Ideone:
http://ideone.com/m1Do1d


To prevent duplicate keys from getting pushed into $array, it works with this code:

<?php

$array = json_decode('[{"1234567":1368356071}]', true);
$array2 = array(array(1234567 => time()), array(7654321 => time()));

var_dump(
    '$array (before)', $array,
    '$array2', $array2
);

foreach ($array2 as $item2) {    
    foreach ($array as $item) {
        if (isset($item[key($item2)])) {
            continue 2;
        }
    }
    $array[] = $item2;
}

var_dump(
    '$array (after)', $array
);

Result:

string(15) "$array (before)"
array(1) {
  [0]=>
  array(1) {
    [1234567]=>
    int(1368356071)
  }
}
string(7) "$array2"
array(2) {
  [0]=>
  array(1) {
    [1234567]=>
    int(1368650316)
  }
  [1]=>
  array(1) {
    [7654321]=>
    int(1368650316)
  }
}
string(14) "$array (after)"
array(2) {
  [0]=>
  array(1) {
    [1234567]=>
    int(1368356071)
  }
  [1]=>
  array(1) {
    [7654321]=>
    int(1368650316)
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top