Pradeep Sanku
Pradeep Sanku

Reputation: 201

required difference keys from 2 array in php

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

Upvotes: 2

Views: 49

Answers (3)

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

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
)

Upvotes: 1

Shobi
Shobi

Reputation: 11461

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

Upvotes: 0

noufalcep
noufalcep

Reputation: 3536

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

Upvotes: 2

Related Questions