i want to check if one array is contained in the second array ,
but the same key and the same values,
(not need to be equal, only check that all the key and value in one array is in the second)
the simple thing that i do until now is :
function checkSameValues($a, $b){
foreach($a as $k1 => $v1){
if($v1 && $v1 != $b[$k1]){
return false;
break;
}
}
return true;
}
Is there a simpler(faster) way to check this ?
thanks
I would do
$array1 = array("a" => "green", "b" => "blue", "c" => "white", "d" => "red");
$array2 = array("a" => "green", "b" => "blue", "d" => "red");
$result = array_diff_assoc($array2, $array1);
if (!count($result)) echo "array2 is contained in array";
What about...
$intersect = array_intersect_assoc($a, $b);
if( count($intersect) == count($b) ){
echo "yes, it's inside";
}
else{
echo "no, it's not.";
}
array_intersect_assoc
array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments.
function checkSameValues($a, $b){
if ( in_array($a,$b) ) return true;
else return false;
}
This obviously only checks depth=1, but could easily be adapted to be recursive:
// check if $a2 is contained in $a1
function checkSameValues($a1, $a2)
{
foreach($a1 as $element)
{
if($element == $a2) return true;
}
return false;
}
$a1 = array('foo' => 'bar', 'bar' => 'baz');
$a2 = array('el' => 'one', 'another' => $a1);
var_dump(checkSameValues($a2, $a1)); // true
Related
First of all - thx for ansvers.
I have got 2 arrays:
For example:
['a' => abc, 'b' => cde]
And second one
['fcb' => cde, 'avm' => efg]
Need to have true of 'b' and 'cde'.
How get a certain similarity for this?
I may be falling into a trap; but, you can compute the intersection (common values) and loop them and search for the key:
$result = array_intersect($array1, $array2);
foreach($result as $val) {
echo "$val found in array1 at key: " . array_search($val, $array1)."<br>\n";
echo "$val found in array2 at key: " . array_search($val, $array2)."<br>\n";
}
See Example.
Assuming that you want to do string search on both keys and values based on your requirement that 'b' should match in both cases:
$a = ['a' => 'abc', 'b' => 'cde'];
$b = ['fcb' => 'cde', 'avm' => 'efg'];
function search($needle, $haystack)
{
foreach(array_merge($haystack, array_keys($haystack)) as $value)
{
if (strpos($value, $needle) !== FALSE)
{
return TRUE;
}
}
return FALSE;
}
echo (int) search('b', $a);
echo (int) search('b', $b);
echo (int) search('z', $a);
echo (int) search('z', $b);
echo (int) search('cde', $a);
echo (int) search('cde', $b);
Output:
110011
I have 2 arrays a and b which may or may not have similar values.
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
I need to check whether the keys that are there in both the arrays contains same values or not using the array functions itself. Please help me.
NB: Array $a is always the parent array. If any key has to be popped, it would be only from $a.
You can use the following comparison based on array_intersect_assoc:
$b == array_intersect_assoc($a, $b)
This will be true when all of the $b key/value pairs occur in $a, false otherwise.
Use this code:
Use: array_diff_key
Remove duplicate key:
<?php
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
$c = array_diff_key($a, $b);
print_r($c); //Array ( [id] => 1 )
?>
Get duplicate key:
Use: array_intersect_key
<?php
function array_duplicate_keys() {
$arrays = func_get_args();
$count = count($arrays);
$dupes = array();
// Stick all your arrays in $arrays first, then:
for ($i = 0; $i < $count; $i++) {
for ($j = $i+1; $j < $count; $j++) {
$dupes += array_intersect_key($arrays[$i], $arrays[$j]);
}
}
return array_keys($dupes);
}
print_r(array_duplicate_keys($a, $b)); //Array ( [0] => name [1] => age )
?>
Get duplicate key and value:
<?php
function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}
$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
}
}
}
return $dups;
}
print_r(get_keys_for_duplicate_values($a, $b));
//Array ( [id] => 1 [name] => John Doe [age] => 35 )
?>
If $b can have keys not present in $a, you can use array_intersect_key two times, with arguments in reversed order and check if both results are the same:
$ab = array_intersect_key($a, $b);
$ba = array_intersect_key($b, $a);
$allValuesEqual = ($ab == $ba);
use this:"it compare both key and value"
$result=array_diff_assoc($a1,$a2); //<-Compare both key and value, gives new array
example:
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","b"=>"pink");
$result=array_diff_assoc($a1,$a2);
print_r($result);
//result will be
Array ( [b] => green )
Array1
(
[a]=>1; [b]=>2; [c]=>3
)
Array2
(
[a]=>1;[b] =>1
)
Required result:
Array1
(
[a]=>2; [b]=>3; [c]=>3
)
How do i append Array1 with the values of Array2 based on their key? Thanks.
You can try something like this:
foreach($array2 as $key2 => $val2){
if(key_exists($key2, $array1)) {
$array1[$key2] += $val2;
} else {
$array1[$key2] = $val2;
}
}
Part of the issue would be that array 1 may not have all of the same keys as array 2. So, an array of all keys from both original arrays is needed, then loop through those keys, check if it exists in either original array, and finally add it to the final combined array.
<?php
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('a' => 1, 'b' => 2, 'd' => 3);
$finalarr = array();
$arrkeys = array_merge(array_keys($array1), array_keys($array2));
$arrkeys = array_unique($arrkeys);
foreach($arrkeys as $key) {
$finalarr[$key] = 0;
if (isset($array1[$key])) {
$finalarr[$key] += $array1[$key];
}
if (isset($array2[$key])) {
$finalarr[$key] += $array2[$key];
}
}
print_r($finalarr);
?>
foreach($array1 as $key=>$value){
if(isset($array2[$key])){
$array1[$key] = $array1[$key] + $array2[$key];
}
}
Not the most elegant way, which would use array_walk or array_map, but I like to see and know exactly what's going on. This will give you what you are looking for.
First sum the values of the common keys and after that, add the others key in the other array:
foreach ($array2 as $k2 => $a2){
if (isset($array1[$k2])){
$array1[$k2]+=$a2;
unset($array2[$k2]);
}
}
$array1 += $array2;
Something like:
$result = array();
function ParseArray(array $array, array &$result)
{
foreach ($array as $k => $v) {
if (!array_key_exists($k, $result) {
$result[$k] = $v;
} else {
$result[$k] += $v;
}
}
}
ParseArray($Array1, $result);
ParseArray($Array2, $result);
print_r($result);
You should read about PHP array functions.
$array1 = array(
'a' => 1,
'b' => 2,
'c' => 3,
);
$array2 = array(
'a' => 1,
'b' => 1,
);
array_walk(
$array1,
function (&$value, $key) use ($array2) {
$value += (isset($array2[$key])) ? $array2[$key] : 0;
}
);
var_dump($array1);
I have a array. for example:
array("Apple", "Orange", "Banana", "Melon");
i want to sort the array that first will be "orange", "melon". and the array will be
array( "Orange" , "Melon","Apple","Banana");
i looked in PHP sort functions, didn't find a s sort function to do it.
what is the right way to do it.
thank you
What you looking for is usort, you can specify custom function to sort the array
example:
function cmp($a, $b)
{
if ($a == "Orange") {
return 1;
}
if ($b == "Orange") {
return -1;
}
return strcmp($a, $b);// or any other sort you want
}
$arr = array("Apple", "Orange", "Banana", "Melon");
usort($arr, "cmp");
Another solution; using a custom function to move an element to the beginning of an array
function __unshift(&$array, $value){
$key = array_search($value, $array);
if($key) unset($array[$key]);
array_unshift($array, $value);
return $array;
}
$a = array("Apple", "Orange", "Banana", "Melon");
__unshift($a, "Melon");
__unshift($a, "Orange");
print_r($a);
Output:
Array
(
[0] => Orange
[1] => Melon
[2] => Apple
[3] => Banana
)
Demo
Or you may use the following to reorder an array using another array having reordered index
function __reorder(&$a, &$b){
$c = array();
foreach($b as $index){
array_push($c, $a[$index]);
}
return $c;
}
// the original array
$a = array("Apple", "Orange", "Banana", "Melon");
// an array with reordered index
$b = array(1, 3, 0, 2);
$c = __reorder($a, $b);
print_r($c);
Demo
$paths = array_merge(
array_intersect(["Orange", "Melon"], ["Apple", "Orange", "Banana", "Melon"]),
array_diff(["Apple", "Orange", "Banana", "Melon"], ["Orange", "Melon"])
);
Here's a solution that's longer than the others provided, but more flexible. You can easily expand or change the array of items that you want sorted first.
$array = array("Apple", "Orange", "Banana", "Melon");
$sort_first = array("Orange", "Melon");
usort($array, function ($a, $b) use ($sort_first) {
$order_a = array_search( $a, $sort_first );
$order_b = array_search( $b, $sort_first );
if ($order_a === false && $order_b !== false) {
return 1;
} elseif ($order_b === false && $order_a !== false) {
return -1;
} elseif ($order_a === $order_b) {
return $a <=> $b;
} else {
return $order_a <=> $order_b;
}
});
// Result: $array = array("Orange", "Melon", "Apple", "Banana");
The function can also be easily altered if the items you're sorting aren't strings, such as arrays or objects. Here's an example that sorts an array of objects:
// Assuming $array is an array of users with a getName method
$sort_first = array("Sam", "Chris");
usort($array, function ($a, $b) use ($sort_first) {
$order_a = array_search( $a->getName(), $sort_first );
$order_b = array_search( $b->getName(), $sort_first );
if ($order_a === false && $order_b !== false) {
return 1;
} elseif ($order_b === false && $order_a !== false) {
return -1;
} elseif ($order_a === $order_b) {
return $a->getName() <=> $b->getName();
} else {
return $order_a <=> $order_b;
}
});
// $array will now have users Sam and Chris sorted first,
// and the rest in alphabetical order by name
Is there any function in PHP which will give an array of uncommon values from two or more arrays?
For example:
$array1 = array( "green", "red", "blue");
$array2 = array( "green", "yellow", "red");
....
$result = Function_Needed($array1, $array2,...);
print_r($result);
Should give the output:
array("blue", "yellow", ...);
Use array_diff and array_merge:
$result = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));
Here's a demo.
For multiple arrays, combine it with a callback and array_reduce:
function unique(&$a, $b) {
return $a ? array_merge(array_diff($a, $b), array_diff($b, $a)) : $b;
}
$arrays = array(
array('green', 'red', 'blue'),
array('green', 'yellow', 'red')
);
$result = array_reduce($arrays, 'unique');
And here's a demo of that.
$result = array_diff($array1, $array2) + array_diff($array2, $array1);
Try array_diff.
This should do it. It can be extended to work with more than two arrays. It basically counts the common key occurrences and returns those with count of one:
$a = array('yellow', 'blue', 'red', 'green');
$b = array('blue', 'purple', 'green');
function unintersect($a, $b)
{
$x = array_fill_keys($a, 1);
foreach ($b as $v) {
$x[$v]++; // this might trigger warning
}
return array_keys(array_filter($x, function($v) {
return $v === 1;
}));
}
print_r(unintersect($a, $b));
Returns:
Array
(
[0] => yellow
[1] => red
[2] => purple
)