Search code examples
phparraysarray-difference

array_diff doesn't seem to be working for me


I'm pulling a feed of YouTube videos from a user account, which are then held in an array.

I've been asked to hide certain videos from the array, so I thought I could do this using array_diff, and creating an array containing the IDs of the videos I want to exclude.

$return = array();
foreach ($xml->entry as $video) {
$vid = array();
$vid['id'] = substr($video->id,42);
$vid['title'] = $video->title;
$vid['date'] = $video->published;
$media = $video->children('http://search.yahoo.com/mrss/');
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$vid['length'] = $attrs['seconds'];
$attrs = $media->group->thumbnail[0]->attributes();
$vid['thumb'] = $attrs['url'];
$yt = $video->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$vid['views'] = $attrs['viewCount'];
array_push($return, $vid);
}

foreach($return as $video) {
$exclude = array('id' => 'zu8xcrGzxQk'); // Add YouTube IDs to remove from feed
$video = array_diff($video, $exclude);

But then overtime I view the page, the video with the ID in the exclude array, is still being shown.

Am I right in thinking, that array_diff will only shows values from array 1 if they are NOT present in array 2?

Is there any reason why the value I've set in the exclude array isn't being removed from the main array?


Solution

  • What you are currently doing is excluding the id key/value from the videos that have that youtube id, you are not removing those videos from $return.

    To remove videos with a given id you need to run an operation on $return you can do that with array_filter, array_diff_key or by filtering them out in the initial loop.

    Using array_filter

    $filter = array('zu8xcrGzxQk', /* other ids */);
    $return = array_filter($return, function ($a) use ($filter) {
       return !in_array($a['id'], $filter);
    });
    

    Using array_diff_key

    In order to do this you need to make the keys of $return the YT ids:

    foreach ($xml->entry as $video) {
       // your old loop code
       // ...
    
       // then instead of array_push you do
       $return[$vid['id']] = $vid;
    }
    
    // now you can do your diff against the keys
    $filter = array('zu8xcrGzxQk', /* other ids */);
    $exclude = array_combine($filter, $filter);
    $return = array_diff_key($return, $exclude);
    

    Filtering in your initial loop instead

    $filter = array('zu8xcrGzxQk', /* other ids */);
    foreach ($xml->entry as $video) {
       $id = substr($video->id,42);
       if (in_array($id, $filter)) {
           continue;
       }
       // the rest of your original loop code
    }