Bug when using array_diff_key() function

Asked

Viewed 30 times

1

Hello, I need to return the difference between two arrays, so I decided to use the native PHP function array_diff_key(), but she doesn’t return anything to me.

<?php

$array1 = array(
0   =>'DENTRO1',
1   =>'DENTRO2',
2   =>'DENTRO3',
4   =>'FORA1',
5   =>'DENTRO4'
);

$array2 = array(
0   =>'DENTRO1',
1   =>'DENTRO2',
2   =>'DENTRO3',
4   =>'FORA2',
5   =>'DENTRO4'
);

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

Does anyone know a way to perform this operation, or what reason/error this example script does not return me anything?

  • This function returns the difference of the arrays using the keys as a means of comparison. If both are composed of 0, 1, 2, 3 in the keys, there will be no difference.

  • if I want to return the difference of the elements, which should I use?

  • 2

    array_diff() only.

  • thanks, just one more question, if I have an array filled by a select, will the array_diff() work ? Example: ($get_sql[] = odbc_result($result, "COLUMNNAME") and ($get_sql2[] = odbc_result($result, "COLUMNNAME2") and using diff($get_sql, $get_sql2) is the correct form?

  • 1

    You will need to convert the object to a Json before, otherwise the array_diff will try to compare the elements inside the query by objects itself. Try to make a array_diff(json_encode($array1), json_encode($array2));.

  • 1

    Perfect friend, thank you so much for your help!!

Show 1 more comment

1 answer

2


You are comparing the two arrays using the keys as the middle between the two arrays. In your example, the keys are identical, so it will not produce the result you expect.

The function you need is the array_diff(), which compares the values of the arrays, and not your keys

<?php

$array1 = array(
0   =>'DENTRO1',
1   =>'DENTRO2',
2   =>'DENTRO3',
4   =>'FORA1',
5   =>'DENTRO4'
);

$array2 = array(
0   =>'DENTRO1',
1   =>'DENTRO2',
2   =>'DENTRO3',
4   =>'FORA2',
5   =>'DENTRO4'
);

$diferenca = array_diff($array1, $array2);

var_dump($diferenca);

Upshot:

array(1) {
    [4] => string(5) "FORA1"
}

Documentation of array_diff_key().

Documentation of array_diff().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.