How to check it elemets of an array are in another array - php

I have an issue,
I have this array
$items= array('ABC','DEF',GHI');
and have another two arrays
$array1 = array('ABC','DEF',GHI');
$array2 = array('DEF');
$array1 should return TRUE because all elements are in $items
$array2 should return FALSE because 'ABC' and 'GHI' arent in that array
i've tried with array_intersect and array_diff but i cant get it,
$result = array_intersect($items,$array1);
$result = !array_diff($items,$array1);
Could you please help me?
Regards
Mario

To see if the array contains at least all values in $items, just get all values from the array that are also in $items and compare it with $items:
$result = (array_intersect($array1, $items) == $items);
If you just need to compare the arrays:
$result = ($array1 == $items);
But why is this not working for you:
$result = !array_diff($items, $array1);

If you dont want to use array_diff, you can use the multidimensional arrays.
Put your arrays inside another array:
$items1= array(
array(0=>"ABC", 1=> "DEF", 2=>"GHI"),
array(0=>"ABC", 1=> "DEF", 2=>"GHI"),
array(0=>"DEF"),
);
Check them with conditional statements:
if($items1[0]==$items1[1]){
echo "true";
}if($items1[1]==$items1[2]){
echo "true 2";
}else{
echo "false";
}

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");

Create an array from arrays that holds data

I am trying to create an array that will hold the only array that contains values.
Code below works well, but I get trouble if for ex, $array2 (but can array1 or array3) doesn't contain any value. In that case, I need to merge only array1 and array3.
$array3 = array_filter( array_map( function( $term ) {
if ( ! $term = \Softing\Term::get( $term ) ) {
return false;
}
return [
'link' => $term->get_link(),
'name' => $term->get_name(),
'color' => $term->get_color(),
];
}, $terms ) );
$formatted_terms[] = array_merge($array1, $array2, $array3);
Each if three arrays are formed on the same way as $array3, but some of them could be empty, no values. Those Arrays I dont want to merge. Want to create array only from arrays that holds value.
What is the easiest way to accomplish this.
I tried using
$formatted_terms[] = array_merge((array)$array1, (array)$array2, (array)$array3);
Any advice ?
You can use array_filter() to remove empty array values. Since you have a multidimensional array, you may consider using array_map() in conjunction with array_filter().
Take the following for example:
$array1 = ['link'=>'foo', 'name'=>'bar', 'filter'=>'hello world'];
$array2 = false;
$array3 = ['link'=>'foo', 'name'=>'bar', 'filter'=>'hello world'];
$formatted_terms[] = array_merge((array)$array1, (array)$array2, (array)$array3);
$formatted_terms = array_map('array_filter',$formatted_terms);
echo '<pre>',print_r($formatted_terms),'</pre>';
https://www.php.net/manual/en/function.array-map.php
https://www.php.net/manual/en/function.array-filter.php
Just check if theyre an array and if theyre not empty. If so, use array merge. If not, just do nothing.
$a_all_arrays = array($array1, $array2, $array3);
$a_merged = array();
foreach($a_all_arrays as $arr)
{
if(is_array($arr) && !is_empty($arr))
{
$a_merged = array_merge($a_merged, $arr);
}
}
Check the array if it has values before merging,
$array1=!empty($array1) && is_array($array1)?$array1:[];
$array2=!empty($array2) && is_array($array2)?$array2:[];
$array3=!empty($array3) && is_array($array3)?$array3:[];
$formatted_terms[] = array_merge($array1, $array2, $array3);

PHP Array_diff when there are duplicate array values

I have two arrays containing repeating values:
$test1 = Array(
"blah1",
"blah1",
"blah1",
"blah1",
"blah2"
);
$test2 = Array(
"blah1",
"blah1",
"blah1",
"blah2"
);
I am trying to get array difference:
$result = array_diff($test1,$test2);
echo "<pre>";
print_r($result);
I need it to return array with single value blah1, yet it returns empty array instead...
I suspect it has something to do with fact there are duplicate values in both arrays, but not sure how to fix it...
Please help!!
EDIT:
End up writing this function to do the trick:
function subtract_array($array1,$array2){
foreach ($array2 as $item) {
$key = array_search($item, $array1);
unset($array1[$key]);
}
return array_values($array1);
}
array_diff compares the first array to the other array(s) passed as parameter(s) and returns an array, containing all the elements present in the first array that are not present in any other arrays. Since $test1 and $test2 both contain "blah1" and "blah2", and no other values, actually, the expected behavior of array_diff is the one that you have experienced, that is, to return an empty array, since, there is no element in $test1 which is not present in $test2.
Further read. Also, read some theory to understand what you are working with.
Spotted a problem with Acidon's own solution. The problem comes from the fact that unset($array[false]) will actually unset $array[0], so there needs to be an explicit check for false (as David Rodrigues pointed out as well.)
function subtract_array($array1,$array2){
foreach ($array2 as $item) {
$key = array_search($item, $array1);
if ( $key !== false ) {
unset($array1[$key]);
}
}
return array_values($array1);
}
Some examples
subtract_array([1,1,1,2,3],[1,2]); // [1,1,3]
subtract_array([1,2,3],[4,5,6]); // [1,2,3]
subtract_array([1,2,1],[1,1,2]); // []
subtract_array([1,2,3],[]); // [1,2,3]
subtract_array([],[1,1]); // []
subtract_array(['hi','bye'], ['bye', 'bye']); // ['hi']

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);
?>

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));

Categories