Remove only one matching element from two arrays - php

$array1 = array(1.99);
$array2 = array(1.99, 1.99, 2.99);
I want to remove only one matching element of $array1, from $array2.
so, What I want is:
1.99
2.99
Ive tried array_diff(), which will take out both of the 1.99 and leave me with only 2.99.

You can take advantage of the fact array_search will only return one matching element from the target array, and use it to remove that from $array2:
$array1 = array(1.99);
$array2 = array(1.99, 1.99, 2.99);
foreach ($array1 as $remove) {
unset($array2[array_search($remove, $array2)]);
}
If $array1 can contain elements that aren't present in $array2 then you'll need to add a check that the result of array_search is not false.

First merge the two arrays the find unique elements .Try array_merge() and array_unique()
<?php
$array1 = array(1.99);
$array2 = array(1.99, 1.99, 2.99);
print_r(array_unique(array_merge($array1, $array2)));
?>

I did similar to #iainn:
foreach($array1 as $k=>$v){
if(in_array($v, $array2)){
unset($array1[$k]);
break;
}
}

Related

How to merge two array and take only value in first array if there is no matching value in second array

I have two arrays :
$array1 = [460,471];
$array2 = [193,42,471];
I want to take the value only in $array1 if there is no same value in $array2, if there is a same value in $array2 filter it out.
Expected output if no same value available in $array2:
$output = [460, 471]
Expected output is there is same value in $array2:
$output = [460]
Try array_diff() function
$array1 = [460,471];
$array2 = [193,42,471];
$filtered = array_diff($array1,$array2);
print_r($filtered);
You can achieve the same with the help of Hashing pretty easily.
First, try to map the values of array2 into a Hash.
For example, each element of $array2 = [193,42,471]; will have a value marking their presence as true.
Now, for each element is $array1, check if it has a value in the Hash. If it has one, then skip it.
So after the check, you will get all the values that are not present in the second array.

PHP Pass multiple values to a foreach function

I am wondering how in PHP would I pass multiple arrays to a for each loop.
For example, in the following I'd want to pass both $array1 and $array2 to this for each loop, rather than have the for each loop written twice.
$array1 = somestring;
$array2 = someotherstring;
foreach ($array1 as $vals) {
//do something cool
}
Edit: To clarify, I am aware that the array declarations are not valid. It is just a placeholder. That does not deserve a downvote. I want to run the entire foreach loop with $array1, and then run it again with $array2.
$array3 = array_merge($array1, $array2);
foreach ($array3 as $vals) {
// do your coolness
}
You can kind of zip two indexed arrays with array_map(null, $array1, $array2). This way you will have a list of tuples, where the first element will be from $array1 and the second - from $array2. You can iterate over this list and access both arrays elements in one iteration.
$array1 = [1, 2, 3];
$array2 = [1, 2, 3];
$zip = array_map(null, $array1, $array2);
foreach ($zip as $tuple) {
echo $tuple[0], '-', $tuple[1], PHP_EOL;
}
Here is demo.
Be aware that your arrays (in this case lists) have to be the same length. Other wise you will end up with broken tuples, one elements of which will be null.

php array_merge and array_intersect usage to merge, filter an array

i need this a lot and i was thinking there must be a way to avoid looping arrays to accomplish this task.
example arrays
$array1 = ['user_id'=>'1','password'=>'PASS','name'=>'joe','age'=>'12'];
$array2 = ['user_id'=>'0','password'=>'default','age'=>'21'];
$filter = ['user_id','password'];
Question is how can i
merge array1 and array2 overwriting array2 with values of array1, and adding missing keys.
merge $array1 with $array2 overwritting $array2 with values from $array1, yet neglect extra data in array1 (above example should neglect name)
how can i unset all array_keys from $array1 which is in $filter
how to only return part of the array from $array1 where keys exist in $filter
without using loops ?
sorry if i ask for alot, but this is meant to collect most usages of array_intersect , array_merge, and array_diff and how to use them correctly.
edit:
Expected output
for 1.
['user_id'=>'1','password'=>'PASS','name'=>'joe','age'=>'12']; //since all array2 was overwritten and extra keys was added
2.
['user_id'=>'1','password'=>'PASS','age'=>'12'];
3.
['age'=>'21']; //removed user_id,password from array1 since they exist in $filter
4.
['user_id'=>'1','password'=>'PASS','age'=>'12'];//return only values of keys that exist in $filter
thanks
1-merge array1 and array2 overwriting array2 with values of array1, and adding missing keys.
$a1 = $a1 + $a2;
2-merge $array1 with $array2 overwritting $array2 with values from $array1, yet neglect extra data in array1 (above example should neglect name)
$a2 = $a2 + $a1;
3-how can i unset all array_keys from $array1 which is in $filter
array_walk($array1, function($val,$key) use(&$array1, $filter) {
if(in_array($key, $filter)) unset($array1[$key]);
});
4-how to only return part of the array from $array1 where keys exist in $filter
array_walk($array1, function($val,$key) use(&$array1, $filter) {
if(!in_array($key, $filter)) unset($array1[$key]);
});

Combine Two Arrays with numerical keys without overwriting the old keys

I don't want to use array_merge() as it results in i misunderstood that all values with the same keys would be overwritten. i have two arrays
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
and would like to combine them resulting like this
array(0=>'foo', 1=>'bar',2=>'bar', 3=>'foo');
array_merge() appends the values of the second array to the first. It does not overwrite keys.
Your example, results in:
Array (
[0] => foo
[1] => bar
[2] => bar
[3] => foo )
However, If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Unless this was just an example to another problem you were having?
Does this answer your question? I'm not sure exactly what you're trying to accomplish, but from your description it sounds like this will work:
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
foreach ($array2 as $i) {
$array1[] = $i;
}
echo var_dump($array1);
If someone stumbles upon this, this is a way to do it nowadays:
var_dump(array_merge_recursive($array1, $array2));
There are probably much better ways but what about:
$newarray= array();
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
$dataarrays = array($array1, $array2);
foreach($dataarrays as $dataarray) {
foreach($dataarray as $data) {
$newarray[] = $data;
}
}
print_r($newarray);
$result = array_keys(array_merge(array_flip($array1), array_flip($array2)));
var_dump($result);

How can I use in_array if the needle is an array?

I have 2 arrays, the value will be loaded from database, below is an example:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
What I want to do is to check if all the values in $arr1 exist in $arr2. The above example should be a TRUE while:
$arr3 = array(1,2,4,5,6,7);
comparing $arr1 with $arr3 will return a FALSE.
Normally I use in_array because I only need to check single value into an array. But in this case, in_array cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.
UPDATE for clarification.
First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.
Use array_diff():
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$arr3 = array_diff($arr1, $arr2);
if (count($arr3) == 0) {
// all of $arr1 is in $arr2
}
You can use array_intersect or array_diff:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
if ( $arr1 == array_intersect($arr1, $arr2) ) {
// All elements of arr1 are in arr2
}
However, if you don't need to use the result of the intersection (which seems to be your case), it is more space and time efficient to use array_diff:
$arr1 = array(1,2,3);
$arr2 = array(1,2,3,4,5,6,7);
$diff = array_diff($arr1, $arr2);
if ( empty($diff) ) {
// All elements of arr1 are in arr2
}
You can try use the array_diff() function to find the difference between the two arrays, this might help you. I think to clarify you mean, all the values in the first array must be in the second array, but not the other way around.
In my particular case I needed to check if a pair of ids was processed before or not. So simple array_diff() did not work for me.
Instead I generated keys from ids sorted alphabetically and used them with in_array:
<?php
$pairs = array();
// ...
$pair = array($currentId, $id);
sort($pair);
$pair = implode('-', $pair);
if (in_array($pair, $pairs)) {
continue;
}
$pairs[$pair] = $pair;
This is probably not an optimum solution at all but I just needed it for a dirty script to be executed once.

Categories