Jump to content

array_merge / array_diff question


Naps

Recommended Posts

I am trying to understand why the following code outputs the value of 4 (it is part of a PHP quiz question). I know that array_diff will compare one array with another and return the result but I just don't understand what is going on with the code below:

 

<?php
$a = array(1,2,4,;
$b = array(0,2,4,6,8,10);
echo count (array_merge(array_diff($a, $b), array_diff($b, $a))); //prints 4
?>

 

Would someone be able to walk me through it?

Link to comment
Share on other sites

I am trying to understand why the following code outputs the value of 4 (it is part of a PHP quiz question). I know that array_diff will compare one array with another and return the result but I just don't understand what is going on with the code below:

 

<?php
$a = array(1,2,4,;
$b = array(0,2,4,6,8,10);
echo count (array_merge(array_diff($a, $b), array_diff($b, $a))); //prints 4
?>

 

Would someone be able to walk me through it?

 

Hiya,

 

I think I'm reading it correctly but working our way out from the middle you have two array_diffs. Well the difference between the two arrays $a and $b are 0 and 10 being present in $b but not $a.

 

Array_diff works by returning an array with the differing pieces from the two arrays you provide. The below is from php.net

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

 

So in this case you are creating two new arrays that have both 0 and 10 as items within them which are then merged together and the items are counted. Which is why it returns 4.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.