PHP find first difference in two multi-dim arrays [duplicate] - php

This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
i have 2 php Arrays and want to compare elements.
examples:
$Array_A[0]["field"]=10; $Array_B[0]["field"]=10;
$Array_A[1]["field"]=20; $Array_B[1]["field"]=30;
$Array_A[2]["field"]=30; $Array_B[2]["field"]=40;
$Array_A[3]["field"]=40;
Array_Difference() should return 20
$Array_A[0]["field"]=10; $Array_B[0]["field"]=10;
$Array_A[1]["field"]=20; $Array_B[1]["field"]=20;
$Array_A[2]["field"]=30; $Array_B[2]["field"]=40;
$Array_A[3]["field"]=40;
Array_Difference() should return 30
For Case that there are more than 1 Difference i would Loop a Function which is finding and return the first found Difference.
What is "best-pratice" to do this Task?

You should use array_diff() combined with array_column.
array_diff(array_column($Array_A, 'field'), array_column($Array_B, 'field'))
array_diff - returns difference between two arrays
array_column - returns one column from multidimensional array
If you want to have only one result then you can use array_shift() which will take the first element from the beginning of an array
f.e
$diff = array_diff(array_column($Array_A, 'field'), array_column($Array_B, 'field'));
$firstDifference = array_shift($diff);

simply, you use array_udiff to create a custom diff function.
This will enable you to access the multidimensional elements.
$result = array_udiff($array1, $array2, function($a, $b){
return $a['field'] <=> $b['field']; // replace the spaceship if not using php7
};

You should probably look at: array_diff
Example #1 array_diff() example
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result); ?> Multiple occurrences in $array1 are all treated
the same way. This will output :
Array (
[1] => blue
)

$Array_A[0]["field"]=10; $Array_B[0]["field"]=10;
$Array_A[1]["field"]=20; $Array_B[1]["field"]=30;
$Array_A[2]["field"]=30; $Array_B[2]["field"]=40;
$Array_A[3]["field"]=40;
$result=your_array_diff($Array_A,$Array_B);
print_r($result);
function your_array_diff($arraya, $arrayb) {
foreach ($arraya as $keya => $valuea) {
if (in_array($valuea, $arrayb)) {
unset($arraya[$keya]);
}
}
return $arraya;
}
Output:
Array ( [1] => Array ( [field] => 20 ) )
Ref: https://stackoverflow.com/a/35071068/2520628

like the previous answers suggested array_diff () will find missing values in the second array of its parameter. however, i guess in your case the position (key) is also important. in that case you could use a simple loop.
foreach ($array1 as $key => $value)
if (array_key_exists ($key, $array2)
if ($array1[$key]['field'] != $array2[$key]['field']){
//do something
break;
}

Related

How to remove an entire row in multidimentional array based on another simple array value

i need to compare the value of an array and based on that i need to check another array which is multidimensional , if the value is present in another array , then i need to delete the entire row from it . how to achieve this ?
<?php
$a1=array(
array("key1"=>"123","phone"=>"2234567890","val"=>"test1","color"=>"red"),
array("key1"=>"234","phone"=>"2234567890","val"=>"test2","color"=>"green"),
array("key1"=>"312","phone"=>"2234567890","val"=>"test3","color"=>"yellow"),
array("key1"=>"425","phone"=>"2234567890","val"=>"test4","color" => "orange"));
$a2=array("green");
foreach($a1 as $k => $value){
$result = array_diff($value, $a2);
print_r($result);
}
?>
I have tried with array_diff , but only that key,val pair is removing .. i need to remove entire row.
$a2 array has value "green" .. based on this array $a1 should have only 3 array as output by removing 2nd array of $a2.
Assuming you compare values of color key:
$a1 = array(
array("key1"=>"123","phone"=>"2234567890","val"=>"test1","color"=>"red"),
array("key1"=>"234","phone"=>"2234567890","val"=>"test2","color"=>"green"),
array("key1"=>"312","phone"=>"2234567890","val"=>"test3","color"=>"yellow"),
array("key1"=>"425","phone"=>"2234567890","val"=>"test4","color" => "orange")
);
$a2 = array("green");
$newArray = array_filter(
$a1,
function($v) use ($a2) { return !in_array($v['color'], $a2); }
);
Fiddle here.
If you don't want to compare a specific key, then just check if it is in the array and unset it:
foreach($a1 as $k => $value){
if(array_intersect($value, $a2)) {
unset($a1[$k]);
}
}
This would also work for checking an array with multiple values like:
$a2 = array("green", "test4");
//or
$a2 = array("green", "red");

PHP to get array_values from 2D array

I have a 2D array like
attendee_programs = [1 =>[100,101],
2 =>[100,101,102]
];
I want to get array_values() and array_unique() but only for the nested elements (sorry, not sure what the terminology is) ...I.E.
programs = [100,101,102];
Is there a php function for this? or do I need to loop through and assemble it manually?
Edit: All of the answers are very helpful and have shown me something new. Sorry I can only accept one.
You could use a clever combination of array_unique, array_reduce and array_merge to achieve this:
$a = array_unique(array_reduce($attendee_programs, 'array_merge', []));
Doing this might be end in an array with some gaps in the indizes - if you need gaples array keys, you have to add array_values at the end
$a = array_values($a);
You can use:
call_user_func_array('array_merge', array_values($attendee_programs));
to get values of nested array.
array_unique(call_user_func_array('array_merge', array_values($attendee_programs)));
to get unique values.
RecursiveIteratorIterator
RecursiveArrayIterator
Solution:
function flatten($array)
{
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
return iterator_to_array($rit, true);
}
echo '<pre>';
print_r(flatten($attendee_programs));
Result:
Array
(
[0] => 100
[1] => 101
[2] => 102
)
Yet another option:
$flat = array();
array_walk_recursive($attendee_programs, function($value) use (&$flat) {
$flat[] = $value;
});
$flat = array_unique($flat);

How to delete duplicates in an array?

How can I delete duplicates in array?
For example if I had the following array:
$array = array('1','1','2','3');
I want it to become
$array = array('2','3');
so I want it to delete the whole value if two of it are found
Depending on PHP version, this should work in all versions of PHP >= 4.0.6 as it doesn't require anonymous functions that require PHP >= 5.3:
function moreThanOne($val) {
return $val < 2;
}
$a1 = array('1','1','2','3');
print_r(array_keys(array_filter(array_count_values($a1), 'moreThanOne')));
DEMO (Change the PHP version in the drop-down to select the version of PHP you are using)
This works because:
array_count_values will go through the array and create an index for each value and increment it each time it encounters it again.
array_filter will take the created array and pass it through the moreThanOne function defined earlier, if it returns false, the key/value pair will be removed.
array_keys will discard the value portion of the array creating an array with the values being the keys that were defined. This final step gives you a result that removes all values that existed more than once within the original array.
You can filter them out using array_count_values():
$array = array('1','1','2','3');
$res = array_keys(array_filter(array_count_values($array), function($freq) {
return $freq == 1;
}));
The function returns an array comprising the original values and their respective frequencies; you then pick only the single frequencies. The end result is obtained by retrieving the keys.
Demo
Try this code,
<?php
$array = array('1','1','2','3');
foreach($array as $data){
$key= array_keys($array,$data);
if(count($key)>1){
foreach($key as $key2 => $data2){
unset($array[$key2]);
}
}
}
$array=array_values($array);
print_r($array);
?>
Output
Array ( [0] => 2 [1] => 3 )
PHP offers so many array functions, you just have to combine them:
$arr = array_keys(array_filter(array_count_values($arr), function($val) {
return $val === 1;
}));
Reference: array_keys, array_filter, array_count_values
DEMO
Remove duplicate values from an array.
array_unique($array)
$array = array(4, "4", "3", 4, 3, "3");
$result = array_unique($array);
print_r($result);
/*
Array
(
[0] => 4
[2] => 3
)
*/

how to get keys that correspond to different values in two arrays?

$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
I need function that would return array('tomato','banana'), consider that it omits keys that don't exist in one or the other array. Apple has the same value in both arrays, so it should be omitted - returned should be only keys whose values differ and are set
This should work (demo):
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$result = array_keys(array_diff(array_intersect_key($arr1, $arr2), $arr2));
print_r($result);
Output:
Array
(
[0] => tomato
[1] => banana
)
Reference:
array_intersect_key — Computes the intersection of arrays using keys for comparison
array_diff — Computes the difference of arrays
array_keys — Return all the keys or a subset of the keys of an array
$array3 = array();
foreach(array_intersect_key($array1, $array2) as $key => $v){
if($array1[$key] != $array2[$key]) $array3[] = $key;
}
<?php
/**
* Returns an array which contains keys which are in both $array1
* and $array2, and which have different values.
*/
function getKeysWhichMatchAndHaveDifferentValues($array1, $array2)
{
$arrIntersected = array_intersect_key($array1, $array2);
foreach($arrIntersected as $key => $value)
{
if($array2[$key] == $value) {
unset($arrIntersected[$key]);
}
}
return array_keys($arrIntersected);
}
$arr1 = array('potato'=>1,'tomato'=>2,'apple'=>5,'banana'=>10);
$arr2 = array('orange'=>20,'tomato'=>3,'apple'=>5,'banana'=>20);
$final = getKeysWhichMatchAndHaveDifferentValues($arr1, $arr2);
echo '<pre>' . print_r($final) . '</pre>';
?>
I would do simple loop.
Of course if you will need to compare large arrays, the native PHP functions could help a lot. Still can't answer right now what would be the most optimal way to do this.
You could do this using array_intersect and array_keys.
$arr3 = array_intersect(array_keys($arr1), array_keys($arr2));

How to compare 2 different length arrays to eachother

I'm trying to make a function that compares two different length arrays to each other and if they match then some actions are performed. Array1, cell1 compares to array2, cell1, cell2, cellN... Then Array1, cell2 compares to array2, cell1, cell2, cellN...
Something resembling this:
if(array1[$i]==array2[])
{
// Some actions...
}
How can this be implemented?
PHP has in_array for searching an array for a particular value. So what about
foreach ($array1 as $search_item)
{
if (in_array($search_item, $array2))
{
// Some actions...
break;
}
}
You can get the difference of the Arrays with the PHP function array_diff.
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Results in
Array
(
[1] => blue
)
You can use nested loops for this.
for($i=0; $i<count($array1); $i++){
for($j=0; $j<count($array2); $j++){
if($array1[$i] == $array2[$j]){
//some action here
}
}
}
kindly correct the errors. im comparing the arrays values to display respectively with their paired one
if((cardnumb1[1]==123456789) && (passcode[1]==1234))
else if ((cardnumb1[2]==987654321) && (passcode[2]==4567))
else if ((cardnumb1[3]==123789456) && (passcode[3]==7890))
Even if answered I think, just for reference, is good to know that you can make:
$array_1 = array(1,2,3,4,5);
$array_2 = array(2,4,6,8);
foreach (array_intersect($array_1,$array_2) as $match){
//do something
}
NOTE: may give some problems with associative arrays.

Categories