PHP Function to get difference element from both arrays - php

Here's the situations:
I have 2 arrays, eg:
$a=array('a','b','c','d');
$b=array('1','b','c','e');
I want to produce 2 arrays with result:
$c=array('a','d');//only element appeared on $a
$d=array('1','e');//only element appeared on $b
Do you have a clever solution?

$c = array_diff($a, $b);
$d = array_diff($b, $a);

Sorry, my bad. It turn out a was giving the wrong array in my test.
simple array_diff solved the problem:
$c = array_diff($a, $b);
$d = array_diff($b, $a);

Try using the array_diff() function:
array_diff(array1,array2,array3...)
eg:
<?php
$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");
$a2=array(3=>"Horse",4=>"Dog",5=>"Fish");
print_r(array_diff($a1,$a2));
?>
Output:
Array ( [0] => Cat )
Source: http://www.w3schools.com/PHP/func_array_diff.asp

Related

php array of arrays to 1D array not getting properly as expected

I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.

Subtracting arrays to get every difference

What I have
$array1 = [1,1,1];
$array2 = [1,1];
What I'm doing:
array_diff( $array1, $array2 );
What I expected:
array(1) { 1 }
What I got
array(0) { }
How do I subtract two arrays to get every discrepancy?
Edit:
My example was incomplete, sorry.
If we also have values like this:
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
I would expect
[1,1,2,1] - [1,1,1,2] = []
array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().
So this should work for you:
<?php
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
function caseCmpSort($a, $b){
return strcasecmp($a, $b);
}
usort($array1, "caseCmpSort");
usort($array2, "caseCmpSort");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
output:
Array ( )
use array_diff_assoc
$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)
try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb
So you should check array key differences too. Have you tried array_diff_assoc()?
http://php.net/manual/en/function.array-diff-assoc.php
From manual:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.
$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));
Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.
$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));
<?php
$n = array(1,1,1);
$m = array(1,1);
$r = array_diff_assoc($n,$m);
var_dump($r);
?>

merge arrays without same values

I have two arrays:
$a = array('a','b','c');
$b = array('b','c','d','e');
What must I do in order to get array ('a','d','e') via array $a and $b?
$a = array('a','b','c');
$b = array('b','c','d','e');
$output = array_merge(array_diff($a, $b), array_diff($b, $a));
I think that is right - is off top of my head.
Yup http://ideone.com/56V0d0 <- fiddle here - seems to work!

Add the elements of $b to the end of array $a in php

I have 2 arrays.
I want to add the elements of $b to the end of $a. I checked google, nothing.
$a=array(1,2,3);
$b=array(4,5,6);
array_push($a,$b);
print_r($a);
My goal is to make $a=(1,2,3,4,5,6) but the above doesn't work correctly...any ideas?
You can use array_merge for that.
you can use array_merge
$c = array_merge($a, $b);
$c = array(1,2,3,4,5,6);
Use array_merge()
$a = array(1,2,3);
$b = array(4,5,6);
$c = array_merge($a, $b);
print_r($c);
You can't use array operator: + as xzyfer pointed out.
It will do a union and only works when the keys don't overlap.

How to compare two arrays and remove matching elements from one for the next loop?

How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?
$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);
$C = array_intersect($A,$B); //equals (1,2,3,4)
$A = array_diff($A,$B); //equals (5,6,7,8)
Is this the simplest way or is there a way to use another function that I haven't thought of? My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.
You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.
Edit:
For example:
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);
Source
Dear easy and clean way
$clean1 = array_diff($array1, $array2);
$clean2 = array_diff($array2, $array1);
$final_output = array_merge($clean1, $clean2);
See also array_unique. If you concatenate the two arrays, it will then yank all duplicates.
Hey, even better solution: array _ uintersect.
This let's you compare the arrays as per array_intersect but then it lets you compare the data with a callback function.
Try to this
$a = array(0=>'a',1=>'x',2=>'c',3=>'y',4=>'w');
$b = array(1=>'a',6=>'b',2=>'y',3=>'z');
$c = array_intersect($a, $b);
$result = array_diff($a, $c);
print_r($result);

Categories