I'm trying to make a function that compares two different length arrays to each other and if they match then some actions are performed. Array1, cell1 compares to array2, cell1, cell2, cellN... Then Array1, cell2 compares to array2, cell1, cell2, cellN...
Something resembling this:
if(array1[$i]==array2[])
{
// Some actions...
}
How can this be implemented?
PHP has in_array for searching an array for a particular value. So what about
foreach ($array1 as $search_item)
{
if (in_array($search_item, $array2))
{
// Some actions...
break;
}
}
You can get the difference of the Arrays with the PHP function array_diff.
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
Results in
Array
(
[1] => blue
)
You can use nested loops for this.
for($i=0; $i<count($array1); $i++){
for($j=0; $j<count($array2); $j++){
if($array1[$i] == $array2[$j]){
//some action here
}
}
}
kindly correct the errors. im comparing the arrays values to display respectively with their paired one
if((cardnumb1[1]==123456789) && (passcode[1]==1234))
else if ((cardnumb1[2]==987654321) && (passcode[2]==4567))
else if ((cardnumb1[3]==123789456) && (passcode[3]==7890))
Even if answered I think, just for reference, is good to know that you can make:
$array_1 = array(1,2,3,4,5);
$array_2 = array(2,4,6,8);
foreach (array_intersect($array_1,$array_2) as $match){
//do something
}
NOTE: may give some problems with associative arrays.
Related
This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
i have 2 php Arrays and want to compare elements.
examples:
$Array_A[0]["field"]=10; $Array_B[0]["field"]=10;
$Array_A[1]["field"]=20; $Array_B[1]["field"]=30;
$Array_A[2]["field"]=30; $Array_B[2]["field"]=40;
$Array_A[3]["field"]=40;
Array_Difference() should return 20
$Array_A[0]["field"]=10; $Array_B[0]["field"]=10;
$Array_A[1]["field"]=20; $Array_B[1]["field"]=20;
$Array_A[2]["field"]=30; $Array_B[2]["field"]=40;
$Array_A[3]["field"]=40;
Array_Difference() should return 30
For Case that there are more than 1 Difference i would Loop a Function which is finding and return the first found Difference.
What is "best-pratice" to do this Task?
You should use array_diff() combined with array_column.
array_diff(array_column($Array_A, 'field'), array_column($Array_B, 'field'))
array_diff - returns difference between two arrays
array_column - returns one column from multidimensional array
If you want to have only one result then you can use array_shift() which will take the first element from the beginning of an array
f.e
$diff = array_diff(array_column($Array_A, 'field'), array_column($Array_B, 'field'));
$firstDifference = array_shift($diff);
simply, you use array_udiff to create a custom diff function.
This will enable you to access the multidimensional elements.
$result = array_udiff($array1, $array2, function($a, $b){
return $a['field'] <=> $b['field']; // replace the spaceship if not using php7
};
You should probably look at: array_diff
Example #1 array_diff() example
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result); ?> Multiple occurrences in $array1 are all treated
the same way. This will output :
Array (
[1] => blue
)
$Array_A[0]["field"]=10; $Array_B[0]["field"]=10;
$Array_A[1]["field"]=20; $Array_B[1]["field"]=30;
$Array_A[2]["field"]=30; $Array_B[2]["field"]=40;
$Array_A[3]["field"]=40;
$result=your_array_diff($Array_A,$Array_B);
print_r($result);
function your_array_diff($arraya, $arrayb) {
foreach ($arraya as $keya => $valuea) {
if (in_array($valuea, $arrayb)) {
unset($arraya[$keya]);
}
}
return $arraya;
}
Output:
Array ( [1] => Array ( [field] => 20 ) )
Ref: https://stackoverflow.com/a/35071068/2520628
like the previous answers suggested array_diff () will find missing values in the second array of its parameter. however, i guess in your case the position (key) is also important. in that case you could use a simple loop.
foreach ($array1 as $key => $value)
if (array_key_exists ($key, $array2)
if ($array1[$key]['field'] != $array2[$key]['field']){
//do something
break;
}
Is there a way within PHP and MySQL to be able to compare 2 different array (list) variables and say how many items are the same
For example,
$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";
Then an echo statement would say how many items are the same. In this example, it would be 2 and this would be echoed.
This is different to most array questions because of the way my site is set up using commas which can make it quite complicated
Try array_intersect() function in php
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r(count($result));
?>
You can count elements in the output array using count() function,
doc link
$array_new1 = explode(',',$array1);
$array_new2 = explode(',',$array2);
$array_1 = array_map('trim', $array_new1);
$array_2 = array_map('trim', $array_new2);
$data =array();
foreach($array_2 as $value){
if(in_array($value,$array_1)){
$data[] = $value;
}
}
echo count($data);
First you have to convert your string to array with trim. Then use
array_intersect to get common values.
$array1 = "hello, bye, google, laptop, yes";
$array2 = "google, bye, windows, no, phone";
$array_new1 = array_map('trim', explode(',', $array1));
$array_new2 =array_map('trim', explode(',', $array2));
$common = array_intersect($array_new1, $array_new2);
print_r($common);
echo count($common);
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);
?>
What is the best and fast way to check data in string duplicate or not ?
$data = "320666,320372,320274,320728,320298,320797,320804,320831,320001,320409,320704,320680,320018,320565,320710,320455,320070,320095,320629,319919,320754,319921,320830,320869,320473,319936,320591,319891,320405,320788,320575,320730,320024,320452,320389,320289,320494,320290,319908,319926,320742,320546,319893,320602,320535,320288,320197,320613,320232,320513,320051,320360,319985,320852,320709,320352,320058,320791,320341,320133,319979,320361,319915,319912,320477,320311,320146,320325,320684,319935,320312,320159,320054,320737,320527,319907,320532,320208,320588,320632,320310,320837,320121,320291,320482,320316,320520,320583,320056,319897,320762,320366,319904,320169,320651,320751,320657,320374,320185,320821,319906,320039,320134,320507,319996,320277,320423,320803,320713,320456,320429,320189,320398,320813,320417,320302,320881,320200,320555,320740,320849,320432,320590,319948,319944,320313,320220,320094,320086,320000,320430,319968,320827,320424,320386,320687,320199,320785,320743,320167,320362,319939,320568,320422,320305,320082,320345,320652,320686,320209,320149,320211,320087,320767,320446,320388,320145,320469,320493,320801,319994,319899,320809,320781,320253,320498,320434,320109,319972,320838,320293,320639,320165,320420,320620,320164,320600,320612,320383,320574,320017,320470,319925,320226,320234,320585,320191,320510,319923,320690,319970,320337";
How can i do that ?
Put those values into an array, remove duplicate values, and then compare that array to the original array. If they're the same there are no duplicates.
$values = explode(',', $data);
var_dump($values == array_unique($values));
Demo
Check the php manual for array_unique function:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
or even faster, but little different method using this function - fast_unique
function fast_unique($input) {
// Code documented at: http://www.puremango.co.uk/?p=1039
return array_flip(array_flip(array_reverse($input,true)));
}
And to make an array from your $data string using something like this:
$d = explode(',',$data);
echo "<pre>";
var_dump($d);
echo "</pre>";
Use explode function to split & then use array_count_values i.e.
$arr = explode($data);
print_t(array_count_values($arr));
This will give you repetition count for each number so that you can check if count is more than one, it is duplicate.
I'm looking for an efficient algorithm for detecting equal values in an array of integers N size. It must return the indices of the matches.
Alas, I can't think of anything more clever then brute force with two loops.
Any help will be appreciated.
Thanks!
You could intersect the array. This finds all the values of array2 that are in array1
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
Would return
Array
(
[a] => green
)
It returns an array with all of the keys and values of the matches. Basically you can provide an infinite number of arguments to the array_insert_assoc:
array_intersect_assoc($base_array, $arr1, $arr2 ...);
It will search $base_array for the values that are in all the subsequent arrays. That means that the key and value will be taken from the $base_array
You could also compare the keys by using:
array_intersect_keys($base_array, $arr1, $arr2, $arr3);
These loops are O(N^2). Is N big? If so, can you sort the array O(NlogN), then scan it O(N)? ... or am I missing something?
You can use a set to hold the recent values. For example,
results = empty list
set = empty set
foreach key, val in array:
if val is not in set: add val to set
else: add key to results
return results
Each look up of set is O(1), so this algo will results in O(n) instead of O(n^2) if nested-loop is used.
In case you want to keep track of multi-occurence like this array 1, 2, 3, 3, 2, 1 you can use a hash table with key is the value and value (of the corresponding key in table) is the list of indices. The result for the given array will look lik {1:0, 5; 2: 1, 4; 3: 2, 3}.
results = empty hashtable
for each key, val in array:
if val is not in results:
results[val] = new list()
results[val].append(key)
return results
Perhaps this?
$arr = array_map('unserialize', array_unique(array_map('serialize', $arr)));
From the question: How to remove duplicated 2-dimension array in PHP?
if ($arr !== array_map('unserialize', array_unique(array_map('serialize', $arr))))
{
// found duplicates
}
You don't have to go through all the array again for each element. Only test an element with the subsequent element in the array:
$array = /* huge array */;
$size = count($array);
for($i = 0; $i < $size; $i++)
{
for($j = $i + 1; $j < $size; $j++) // only test with the elements after $i
{
if($array[$i] == $array[$j])
return true; // found a duplicate
}
return false; // found no duplicate
}
That's the most efficient way I can think of. Adapt it to your need as you will.
If one of your arrays is reasonably static (that is you are comparing to the same array several times ) you could invert it.
That is set up another array which is keyed by value and returns the index into the real array.
$invert = array();
foreach ($cmptoarray as $ix => $ival) {
$invert[$ival] = $ix;
}
Then you simply need an if ( isset($invert[$compfrmarray[$i]) ) .... to check the number.
Note: this is only worth doing if you compare against the same array several times!
Just use an associative array mapping a value to its index:
foreach($array1 as $index => $value) {
$aa[$value] = $index;
}
foreach($array2 as $index => $value) {
if(isset($aa[$value])) {
echo 'Duplicate: . Index 1: '.$aa[$value].' Index 2: '.$index.'.';
}
}