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

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.

Related

Php single Array Comparison

I have two arrays.
For example
$arr1 = ['apple','mango','grapes','banana'];
$arr2 = ['apple','mango','orange'];
Now I want to compare these two arrays and make it as
$arr3 = ['apple','mango','grapes','banana']
That is, compare $arr2 with $arr1. If the value of $arr2 exists(apple and mango) in $arr1, then add it in $arr3 otherwise remove that element from $arr2 (orange).
Note: $arr1 values remains the same. i.e - should not remove grapes and banana
I have tried array_intersect and array_unique. But struck with the logic.
#vinothini simply do it with array_intersect() and array_diff() like below:
<?php
$arr1 = ['apple','mango','grapes','banana'];
$arr2 = ['apple','mango','orange'];
$arr3 = array_merge(array_intersect($arr2, $arr1), array_diff($arr1, $arr2));
print_r($arr3);
But the main thing about your answer is that in your case $arr3 will alway equals to $arr1 you don't have to calculate anything so right answer is:
$arr3 = $arr1
you can directly take $arr1 as your desired array()
This code will do.
$arr3 = array_intersect($arr1, $arr2);
$arr4 = array_diff($arr1,$arr3);
$output = array_merge($arr3,$arr4);

if two array has identical values in same format irrespective of key without using any loop

array1 = (a=>1, b=>2, c=>3, d=>1 )
array2 = (g=>1, d=>2, f=>3, e=>1 )
I cannot use === operator as keys are different. The above two arrays has same value format, want to display yes if they have, I can always run a loop but want to avoid that part.
You may be looking for array_values():
<?php
$array1 = ['a'=>1 ,'b'=>2, 'c'=>3, 'd'=> 1];
$array2 = ['g'=>1 ,'d'=>2, 'f'=>3, 'e'=> 1];
var_dump(array_values($array1)===array_values($array2)); // bool(true)
?>
You can temporary standardize the key first using array_values() function.
$tmp1 = array_values(array1);
$tmp2 = array_values(array2);
if($tmp1 === $tmp2) echo 'yes';

PHP renumber array but keep sequence

I have an array like this:
array(13,4,7,1,16);
I want to recount the array, but I want to keep the sequence, like this:
array(4,2,3,1,5);
How can I do this?
If you are trying to sort the array, keeping the keys in the same order as the values, the PHP asort() function does that.
If you want to keep the original array but get the keys in sort order, then you can use something like:
$arr = array(13,4,7,1,16);
asort($arr);
$keys = array_keys($arr);
Then $keys has the keys from the original array sorted in the order of the original values, e.g. $keys = array(4,2,3,1,5);
if you want to get the index of the array with reference to the sorted values
Try this
$numbers = array(13,4,7,1,16);
$numberscopy = $numbers;
sort($numberscopy);
$final = array();
//echo array_search(13, $numbers);
for($a=0 ; $a<count($numberscopy );$a++){
$final[] = array_search($numberscopy[$a], $numbers) + 1;
}
var_dump($final);

PHP: How to compare keys in one array with values in another, and return matches?

I have the following two arrays:
$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden');
$array_two = array('colorOne', 'colorTwo', 'colorThree');
I want an array from $array_one which only contains the key-value pairs whose keys are members of $array_two (either by making a new array or removing the rest of the elements from $array_one)
How can I do that?
I looked into array_diff and array_intersect, but they compare values with values, and not the values of one array with the keys of the other.
As of PHP 5.1 there is array_intersect_key (manual).
Just flip the second array from key=>value to value=>key with array_flip() and then compare keys.
So to compare OP's arrays, this would do:
$result = array_intersect_key( $array_one , array_flip( $array_two ) );
No need for any looping the arrays at all.
Update
Check out the answer from Michel: https://stackoverflow.com/a/30841097/2879722. It's a better and easier solution.
Original Answer
If I am understanding this correctly:
Returning a new array:
$array_new = [];
foreach($array_two as $key)
{
if(array_key_exists($key, $array_one))
{
$array_new[$key] = $array_one[$key];
}
}
Stripping from $array_one:
foreach($array_one as $key => $val)
{
if(array_search($key, $array_two) === false)
{
unset($array_one[$key]);
}
}
Tell me if it works:
for($i=0;$i<count($array_two);$i++){
if($array_two[$i]==key($array_one)){
$array_final[$array_two[$i]]=$array_one[$array_two[$i]];
next($array_one);
}
}

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