PHP compare two arrays and get the difference - php

I have two arrays
$original = array(
array('fruit' => 'appel','color' => 'green'),
array('fruit' => 'Banana','color' => 'Yellow'),
array('fruit' => 'orange','color' => 'orange',)
);
and
$new = array(
array('fruit' => 'appel'),
array('fruit' => 'orange')
);
Now i want to compare the two arrays and print out the different one.
In this case i want to keep
array('fruit' => 'Banana','color' => 'Yellow')
When i use array_intersect_key
$original_new = array_intersect_key($new, $original);
it's deleting the array i want to keep.
I thought i do this:
$original_new = array_intersect_key($new, $original);
$original_new = array_diff($original_new, $original);
But this is of course not working.
Can somebody help me out whit this?

Using some loop and array. Check Online.
First make the array from $new array with the column only, and using the foreach loop over the $original array just check the fruit is in the $new array or not, if not than store the complete sub array in an array name $arr.
$arr = array();
$com = array_column($new, 'fruit');
foreach($original as $value){
if(!in_array($value['fruit'], $com)){
$arr[] = $value;
}
}
print_r($arr); //Array ( [0] => Array ( [fruit] => Banana [color] => Yellow ) )

Just to provide a different point of view,
You can get the solution using some array functions
you just need to get array_column fruit of $new array and same of $original array, get the array_diff of the 2 arrays, finally get the key ,
just try this:
$res = $original[key(array_diff(
array_column($original,'fruit'), array_column($new,'fruit')))];

You can do it without writing own code:
$res = array_intersect_key($original,
array_diff(array_column($original, 'fruit'),
array_column($new, 'fruit')));
demo

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"2.00");
$a2=array("a"=>"red","b"=>"green","c"=>"2");
$r = array_diff_assoc($a1, $a2);
print_r($r);
You can use array_diff_assoc (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
But note that the comparison is strict (===)
The result for the code above:
Array
(
[c] => 2.00
)

(PHP 4 >= 4.0.1, PHP 5, PHP 7)
array_diff — Computes the difference of arrays
Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
print_r($result);
This will return
Array ( [d] => yellow )

Related

Combine dynamic arrays with dynamic keys in to single arrays

I have this dynamic multiple arrays that I need to combine in one array and serialized them. The problem is I need to keep both key and value.
$arr = array($bet_option_id => $bet_option_name);
Here i need to keep both bet_option_id AND bet_option_name. Then this result output:
Array ( [997650802] => Over 2.5 )
Array ( [997650807] => Yes )
This need to be simply
Array
(
[997650802] => Over 2.5
[997650807] => Yes
)
As it's dynamic, sometimes not comes with just single array so apparently I couldn't get it working. I need to retrieve both bet_option_id & bet_option_name. Tried something like this:
$arr = array($bet_option_id => $bet_option_name); //This is where all array keys, values are stores
$result = array();
foreach ($arr as $array) {
$result = array_merge($result, $array);
}
Any inputs will be nice.
Rather than create individual arrays like...
$arr = array($bet_option_id => $bet_option_name);
If you first create an empty array ( like you do with $result)
$arr = array();
and then add each item in using
$arr[$bet_option_id] = $bet_option_name;
Then you don't need to manipulate the array after - just create it as you want it in the first place.
You could either do like Nigel Ren suggested which is the most elegant solution
In case that you do not have arrays that their keys are entirely numeric you may use array_merge. The quote following is from PHP array-merge
Example #2 Simple array_merge() example
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
Don't forget that numeric keys will be renumbered!
Array
(
[0] => data
)
Alternatively you can always join arrays together like this
$a1 = [ 997650802 => 'Over 2.5' ];
$a2 = [ 997650807 => 'Yes' ];
var_dump( $a1 + $a2 ); // result is [997650802 => 'Over 2.5',997650807 => 'Yes']
You can check more about Array Types and Array Operators

associative array in sort using php

$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
Array
(
[0] => 5
[1] => 4
[2] => 1
[3] => 2
)
Expecting result
Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
)
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
$results = [];
foreach($array as $key=>$value){
$results[$key] = arsort($value);
}
echo "<pre>";
print_r($results);
Please suggest how do we can sort associative array i did try but does not work for me please guide
As per your "expected results' it seems like you don't wish to maintain the keys. If that's the case then you can just use sort.
Something like this..
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
Just do
sort($array);
Also check the PHP documentation if you need further customization: http://php.net/manual/en/function.sort.php
var_dump( array_reverse($array,false));
you don't need to use foreach or sort ,you can just use array_reverseinstead ,avery simple way
You don't need to iterate using foreach for sorting
Just use sort for sorting array
$array = array('0'=>'5', '1'=>'4', '2'=>'1', '3'=>'2');
sort($array);
print_r($array);
This will not maintain array keys and if you want arrays keys to be same just replace sort with asort in above code

Array_unshift like function that returns the array

is there a built in function in php that prepends an element to an array, and returns the new array?
instead of returning the new length of the array?
You could use
array_merge()
For example
$resultingArray = array_merge(array($newElement), $originalArray);
Next to array_merge, if there ain't any duplicate keys, you can do:
$array = array('a' => 'A');
$append = array('b' => 'hello');
$array = $append + $array;
Gives:
Array
(
[b] => hello
[a] => A
)
The plus is the array union operator­Docs.
There's no built-in which does it, but it's simple enough to wrap it:
function my_unshift($array, $var) {
array_unshift($array, $var);
return $array;
}
This isn't necessary though, because array_unshift() operates on an array reference so the original is modified in place. array_push(), array_pop(), array_shift() all also operate on a a reference.
$arr = array(1,2,3);
array_unshift($arr, 0);
// No need for return. $arr has been modified
print_arr($arr);
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)

How to compare arrays and extract the difference?

I have two arrays that I would like to compare and ultimately wind up with a single array with everything combined, having no duplicates. Can someone please tell me which function I should use? There are so many that it's a bit confusing.
$array1[]['name'] = 'Kim, Jones';
$array1[]['name'] = 'Jim, Miller';
array1 is an array I built that I want added to an array coming from the database. The key in the second array is also named "name". Thanks.
EDIT:
I managed to merge these two arrays but I can still see duplicates.
This is what the first array looks like:
Array
(
[0] => Array
(
[WNumber] => ADMIN
[Name] => Tim, Cooley
[Employer] => CalPERS
[Student] => 1
[Perm] => 1
[QA] => 0
[Supervisor] => 1
[RQW] => 0
)
My second array is built like this:
$add_names[]['Name']='Jim, Jones';
I just want to add $add_names to the first array WHERE there are no duplicates.
I'm tempted to sell you on CakePHP, since it has a number of functions that makes this easy in its "Set" class. Your problem is that you have the results in a nested array. A simple "array_unique" does not work in a nested array.
I'd do it the old fashioned way...
$array1[]['name'] = 'Kim, Jones';
$array1[]['name'] = 'Jim, Miller';
$array2[]['name'] = 'Kim, Jones';
$array2[]['name'] = 'Jimbo, Miller';
$array2[]['name'] = 'Jim, Jones';
$new_array=array_merge($array1, $array2);
$out_array = array();
$key_array = array();
foreach($new_array as $i => $row) {
if (empty($key_array[$row['name']])) {
$out_array[] = $row;
}
$key_array[$row['name']] = 1;
}
print_r($out_array);
This code works for me...
I think you'll need to use a combination of array_merge (adds the two arrays together) and array_unique (removes duplicate values).
$resulting_array = array_unique(array_merge($array1, $array2));
Note that array_unique will not work correctly when using multi-dimensional arrays, so if your array data looks the way you put it in your question, you'll have to think of a way around that. One of the comments on the array_unique page suggests serialize'ing all array values before running array_unique on it. Afterwards you'd just run unserialize on all array elements. Note that this can mean a performance hit if you have a big array, so you might want to consider avoiding multi-dimensional arrays in this scenario.
Something like this:
$merged_array = array_merge($array1, $array2);
$serialized_array = array_map("serialize", $merged_array);
$filtered_array = array_unique($serialized_array);
$final_array = array_map("unserialize", $filtered_array);
There isn't a direct function for handling what you are looking for in php, probably you need to write a function for it.
What I understood from your question is that you have 2 arrays :
$a = array( array( 'name' => 'Omid' ), 12 );
$b = array( array( 'name' => 'testing' ) );
and you want to merge them to get
$merge = array( array( 'name' => 'testing' ), 12 );
if that's what you want then you might want to take a look at this comment array merge recursive which leads to this code :
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;
foreach ( $array2 as $key => &$value )
{
if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}
return $merged;
}
Does php's array_diff() do what you want?
http://us.php.net/manual/en/function.array-diff.php
or more likely array_diff_assoc:
http://us.php.net/manual/en/function.array-diff-assoc.php
Does array_diff work for you?
Description
array array_diff ( array $array1 , array $array2 [, array $ ... ] )
Compares array1 against array2 and returns the difference.

Merging and array by value instead of key in PHP

I have two arrays of values that I would like to combine - but the only methods that PHP provides seem to combine by key instead of value. Here is a hack that I was able to use to get this to work, but I am wondering if there is a better method or a native function that I have missed. It's been a while since I last used arrays and it seems like there is an easy answer to this.
//Input arrays that we want to combine into one array
$array = array(2, 3, 4, 5);
$array2 = array(5, 6, 1);
//Flip values and keys
$array = array_flip($array);
$array2 = array_flip($array2);
//Combine array
$array3 = $array2 + $array;
//flip array keys back to values
$array3 = array_keys($array3);
//Optional sort
sort($array3);
print_r($array3);
Which returns the combined values of the two arrays:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Not entirely sure what you are trying to accomplish. I am assuming you are trying to combine 2 arrays without having any duplicates. If this is the case then the following would work
$newarr = array_unique(array_merge($array, $array2));

Categories