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
https://forums.phpfreaks.com/topic/258396-array_merge-array_diff-question/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.