I have an array containing rows of associative data.
$array1 = array( array('ITEM' => 1), array('ITEM' => 2), array('ITEM' => 3), );
I have a second array, also containing rows of associative data, that I would like to filter using the first array.
$array2 = array( array('ITEM' => 2), array('ITEM' => 3), array('ITEM' => 1), array('ITEM' => 4), );
This feels like a job for array_diff()
, but how can I compare the rows exclusively on the deeper ITEM
values?
How can I filter the second array and get the following result?
array(3 => array('ITEM' => 4))
To compare array's structure, You should use identity operator. The only difference(s) between this and my answer is that instead of using == for the elements in the array, it will use === , and with === it checks the order of key value pairs.
Associative array — An array where each key has its own specific value. Multidimensional array — An array containing one or more arrays within itself.
Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.
A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns (think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays.
You can define a custom comparison function using array_udiff()
.
function udiffCompare($a, $b) { return $a['ITEM'] - $b['ITEM']; } $arrdiff = array_udiff($arr2, $arr1, 'udiffCompare'); print_r($arrdiff);
Output:
Array ( [3] => Array ( [ITEM] => 4 ) )
This uses and preserves the arrays' existing structure, which I assume you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With