Archives for 

array difference

Subtracting two dimensional arrays in PHP

In the development a WordPress plugin I had to subtract two dimensional arrays. I tried array_diff() function, unfortunately it doesn’t seem to work for two dimensional arrays. Even if it worked, it wasn’t exactly the functionality I wanted.

Be warned, this isn’t exactly a alternate for array_diff(). For difference of two dimensional arrays you may try this (I dint try it)

I had these two arrays, which I had to subtract.

Array (
 [thumbnail] => Array ( [width] => 150 [height] => 150 [crop] => 1 )
 [medium] => Array ( [width] => 300 [height] => 300 [crop] => )
 [large] => Array ( [width] => 1024 [height] => 1024 [crop] => )
 [full-post-thumb] => Array ( [width] => 576 [height] => 150 [crop] => 1 )
 [popular-posts-home] => Array ( [width] => 210 [height] => 90 [crop] => 1 )
 [popular-posts-widget] => Array ( [width] => 32 [height] => 32 [crop] => 1 )
 [mag1] => Array ( [width] => 170 [height] => 0 [crop] => 1 )
 [mag2] => Array ( [width] => 284 [height] => 0 [crop] => 1 )
 [blog-thumb] => Array ( [width] => 135 [height] => 90 [crop] => 1 )
 [slider1] => Array ( [width] => 250 [height] => 130 [crop] => 1 )
 [slider2] => Array ( [width] => 576 [height] => 280 [crop] => 1 )
)

Array (
 [full-post-thumb] => Array ( [width] => 576 [height] => 150 [crop] => 1 )
 [popular-posts-home] => Array ( [width] => 210 [height] => 90 [crop] => 1 )
 [popular-posts-widget] => Array ( [width] => 32 [height] => 32 [crop] => 1 )
 [mag1] => Array ( [width] => 170 [height] => 0 [crop] => 1 )
 [mag2] => Array ( [width] => 284 [height] => 0 [crop] => 1 )
 [blog-thumb] => Array ( [width] => 135 [height] => 90 [crop] => 1 )
 [slider1] => Array ( [width] => 250 [height] => 130 [crop] => 1 )
 [slider2] => Array ( [width] => 576 [height] => 280 [crop] => 1 )
)

The result I wanted was this, but array_diff() returned null.

Array (
 [thumbnail] => Array ( [width] => 150 [height] => 150 [crop] => 1 )
 [medium] => Array ( [width] => 300 [height] => 300 [crop] => )
 [large] => Array ( [width] => 1024 [height] => 1024 [crop] => )
)

So, I used array_keys() function to get the keys of the second array, and ran a foreach loop on the value returned by array_keys, and unset the elements of first array


$key_names= array_keys ( $array2 );
foreach( $key_names as $key ){
unset($array2[$key]);
}