2

I have following 2 arrays,

1)

Array
    (
        [109] => 0
        [112] => 10
        [113] => 0
        [110] => 0
    )

2)

Array
    (
        [112] => 10.00
    )

now i want output as

Array

(
        [109] => 0
        [113] => 0
        [110] => 0
    )

here [112] i dont want because it is same i want difference. i used array_diff(arr1,arr2); but i am getting [112]. how can i get rid of 112. since 10 and 10.00 is same in value

3

3 Answers 3

2

That's because your values are string. So 10 and 10.00 are different values. Do change all values to int or float.

$arr1 = array_map('floatval', $arr1);
$arr2 = array_map('floatval', $arr2);

array_diff($arr1, $arr2);
2
  • the op wants to calculate the difference in the array_keys, not the values
    – Shobi
    Oct 4, 2018 at 6:22
  • 1
    In the question, he is mentioning the values are same.
    – noufalcep
    Oct 4, 2018 at 6:25
1

You can use array_diff_key function. For example:

$arr1 = [
    109 => 0,
    112 => 10,
    113 => 0,
    110 => 0
];

$arr2 = [
    112 => 10.00
];


print_r(array_diff_key($arr1, $arr2));

Output:

Array
(
    [109] => 0
    [113] => 0
    [110] => 0
)
0

what you need is a variation of array_diff which is array_diff_keywhich will compute difference on keys rather than the values.

$result = array_diff_key($array1,$array2)
var_dump($result);

doc_link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.