1

I got an empty array when I compare two arrays that have the different key but the same value. Example: id has the same value like yy

$o = array('id'=>2,'name'=>'D','yy'=>12); 
$n = array('id'=>12,'name'=>'D','yy'=>12);

What I want is :

$a = array('id'=>12,'id'=>2);
2
  • well you can get both id values on those array, you can't have the same keys in the same array though Commented Feb 23, 2016 at 7:29
  • This function array_diff() compares the values of multiple arrays, and return an array that contains the entries from first array that are not present in another array. so using this function you cannot get values from both arrays. Commented Feb 23, 2016 at 8:15

2 Answers 2

1

You can use array_merge_recursive() - (PHP 4 >= 4.0.1, PHP 5, PHP 7)

From PHP Manual:

array_merge_recursive — Merge two or more arrays recursively

<?php

$a = array('id'=>2,'name'=>'D','yy'=>12); 
$b = array('id'=>12,'name'=>'D','yy'=>12);

$result = array_merge_recursive($a, $b);

$newArr = $result['id']; // get ID index. you can also get other indexes.

echo "<pre>";
print_r($newArr);

?>

Result:

Array
(
    [0] => 2
    [1] => 12
)

Note that: you can not use same index name (ID) for this array array('id'=>12,'id'=>2);

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

Comments

0

As @Ghost mentioned, an associative array should not have the same keys.
I suggest to achieve the "expected result" in "nested arrays" manner using array_diff_assoc function(computes the difference of arrays with additional index check):

$o = array('id'=>2,'name'=>'D','yy'=>12); 
$n = array('id'=>12,'name'=>'D','yy'=>12);

echo "<pre>";

$result_nested_arr = [array_diff_assoc($o, $n), array_diff_assoc($n, $o)];

var_dump($result_nested_arr);

// the output:
 array(2) {
  [0]=>
  array(1) {
    ["id"]=>
    int(2)
  }
  [1]=>
  array(1) {
    ["id"]=>
    int(12)
  }
}

http://php.net/manual/en/function.array-diff-assoc.php

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.