Naps Posted March 6, 2012 Share Posted March 6, 2012 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? Quote Link to comment https://forums.phpfreaks.com/topic/258396-array_merge-array_diff-question/ Share on other sites More sharing options...
Anon-e-mouse Posted March 6, 2012 Share Posted March 6, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/258396-array_merge-array_diff-question/#findComment-1324520 Share on other sites More sharing options...
PFMaBiSmAd Posted March 6, 2012 Share Posted March 6, 2012 The first array_diff() returns an array with 1 in it. The second array_diff() returns an array with 0,6,and 10 in it. The array_merge produces an array with 1,0,6, and 10 in it, having a count of 4. Quote Link to comment https://forums.phpfreaks.com/topic/258396-array_merge-array_diff-question/#findComment-1324524 Share on other sites More sharing options...
Naps Posted March 6, 2012 Author Share Posted March 6, 2012 Thanks for the quick response and explanation guys, I understand now. Quote Link to comment https://forums.phpfreaks.com/topic/258396-array_merge-array_diff-question/#findComment-1324527 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.