I wish to determine whether there are any duplicates in two arrays, i.e. duplicates in array1 or duplicates in array2. If there are, then set a variable to equal 1, otherwise 0. I have the following code but it does not seem to work and I cannot understand why:
$a = count(array_unique($myarraydf));
$b = count($myarraydf);
$c = count(array_unique($myarrayds));
$d = count($myarrayds);
if (($a == $b) || ($c == $d)) {
$ties = 0;
}
else {
$ties = 1;
}
where $myarraydf and $myarrayds are arrays of numeric values.
If you want to set $ties = 1 if there are duplicates in either set, you need to change your operator to AND:
if (($a == $b) and ($c == $d)) {
If you want to set $ties = 1 if both contain duplicates, then the OR is correct.
I suggest using array_diff, see: http://us3.php.net/array_diff
Related
i want to compare two values in one php array but the code stops when i compare even when the conditions is true i want to know how can i compare the two values here is my code :
$i=0;$cmpt=0;
foreach($newarray as $newarray1){
$j=0;
while ($newarray1[$i]!==$newarray1[$j]){ // the iteration dont get in here even when the condition is true
$j+1;
var_dump($j);
}
if ($i=$j){
$couleur[]=$Tcouleur[$cmpt];
$cmpt+1;
}else{
$couleur[]=$Tcouleur[$j];
}
$i+1;
}
var_dump($couleur);
This is probably because of the line
$j+1;
your both variables ($i and $j) are not being updated in the while loop, causing an infinite loop. ( checking the same values all the time, if the condition is true an infinite loop, else the code will never enter the loop and exit. )
change $j+1; with either $j++; or $j = $j + 1;
Moreover as #apomene shows,
if your array can have multiple types,
The !== operator checks both the type and the equality. If your array has same types ( for e.g int ) this would not create a problem tho. With the same types !== and != are the same thing practically. Else, it (!==) also checks for type equality. To elaborate,
$a = 1;
$b = '1';
$c = 2;
$d = 1;
$a == $b // TRUE ( different type, equal after conversion - char <-> int)
$a === $b // FALSE( different types - int vs char)
$a == $c // FALSE( same type not equal)
$a === $d // TRUE ( same type and equal)
Further reading available in this question.
Lastly, you seem to have a confusion between assignment and comparison of a variable. ( $i = $j vs $i == $j )
Check the php manual for assignment vs comparison of variables.
In your while loop, does $j+1 should not be $j++ or $j = $j + 1 ?
I know it's not the problem your asking...but same for your $i+1 at the end and your $cmpt
Now I think you want this :
$values = ['abc','def', 'hij','klm', 'def', 'klm','nop'];
$couleurs = ['rouge','vert','bleu','jaune','rose'];
$couleurPourValeur = [];
$increment = 0;
foreach($values as $value){
if(!isset($couleurPourValeur[$value])){
$couleurPourValeur[$value] = $couleurs[$increment];
$increment++;
}
}
print_r($couleurPourValeur);
$c1 = $v1 = array();
$v1['key'] = 'value';
echo '$c1 === $v1: ' . (($c1 === $v1) ? 'true' : 'false'); // prints false
$c1 === $v1 is false. But why? It seems that $v1 is automatically set to a different array then it's origin array automatically. Why it is happening?
Initially $c and $v1 is set to the same array instance. So if I mutate $v1 should not $c reflects the changes as they are set to the same array instance.
These will not be the same, because you explicitly set them to hold different values. The first is empty, while the second holds values.
They are not set to the same reference though, so they are two different variables - when you do
$c1 = $v1 = array();
You create two different arrays. If you want the change of one to reflect in both arrays, you need to make it a reference, by using the & operator in front of the variable identifier, like so.
$v1 = array();
$c1 = &$v1; // $c1 is now a reference to $v1
$v1['key'] = 'value';
echo '$c1 === $v1: ' . (($c1 === $v1) ? 'true' : 'false'); // true!
Notice that you need to reference it after the variable you wish to refer to has been made.
When using a reference like this, it goes both ways - any change to $v1 would be applied to $c1, and the other way around. So they are different variables, but will always hold the same values.
The comparison in the example above holds true because the arrays are exactly the same - not just by reference, but because they hold the same values and keys. If you compare two non-referenced arrays with the exact same values and exact same, matching keys, you would get a true equality too.
var_dump(array('foo') === array('bar')); // false; same keys, different values
var_dump(array('bar') === array('bar')); // true; same keys, same values
var_dump(array('bar') === array('baz' => 'bar')); // false; different keys, same value
Live demo
Passing variables by reference
Because they are two different object, with two different references, with happening one does not affect the other. Just simple like that.
Those arrays will not be the same because the second array has a value. Please run the following code:
<?php
$a = $b = [];
print_r($a);
print_r($b);
$result = ($a === $b) ? 1 : 0;
// The reasult will be 1 because the arrays are both empty.
print_r($result);
$b[0] = 'Ravi';
print_r($a);
print_r($b);
$result = ($a === $b) ? 1 : 0;
// The result will be 0 because the arrays are different.
print_r($result);
I wondered if there is any way to check if any of a large amount of variables are equal.
If I only have a few variables I can just do this:
if ($a == $b || $a == $c || $b == $c)
However, if I have 20 variables it will take some time to write all combinations. Is there another method?
if (count(array_unique(array($a, $b, $c), SORT_REGULAR)) === 1) {
// all equal
}
All this code does is place the variables in an array and eliminates duplicates. If they are all equal the result of array_unique() should be an array with one value.
If you want to make sure all of them are different it's not much different. Just check to see if the filtered array is the same size as the original array:
$array = array($a, $b, $c);
if (count(array_unique($array, SORT_REGULAR)) === count($array)) {
// all not equal
}
If I have a variable which is given a string that could also be a number, as so:
$a = "1";
If I want to check if it is indeed equal to 1, is there any functional difference between
if((int)$a == 1) {
whatever();
}
and
if($a == "1") {
whatever();
}
Here I am thinking about PHP, but answers about other languages will be welcome.
$a = "1"; // $a is a string
$a = 1; // $a is an integer
1st one
if((int)$a == 1) {
//int == int
whatever();
}
2nd one
if($a == "1") {
//string == string
whatever();
}
But if you do
$a = "1"; // $a is a string
if($a == 1) {
//string & int
//here $a will be automatically cast into int by php
whatever();
}
In the first case you need to convert and then compare while in the second you only compare values. In that sense the second solutions seems better as it avoids unnecessary operations. Also second version is safer as it is possible that $a can not be casted to int.
since your question also asks about other languages you might be looking for more general info, in which case dont forget about triple equals. which is really really equal to something.
$a = "1";
if ($a===1) {
// never gonna happen
}
$b = 1;
if ($b === 1) {
// yep you're a number and you're equal to 1
}
Is there a built-in function for PHP for me to check whether two arrays contain the same values ( order not important?).
For example, I want a function that returns me true for the following two inputs:
array('4','5','2')
array('2','4','5')
Edit: I could have sorted the two arrays and compare them, but as I am such a lazy guy, I would still prefer a one-liner that I can pull out and use.
array_diff looks like an option:
function array_equal($a1, $a2) {
return !array_diff($a1, $a2) && !array_diff($a2, $a1);
}
or as an oneliner in your code:
if(!array_diff($a1, $a2) && !array_diff($a2, $a1)) doSomething();
The best solution is to sort both array and then compare them:
$a = array('4','5','2');
$b = array('2','4','5');
sort($a);
sort($b);
var_dump($a === $b);
As a function:
function array_equal($a, $b, $strict=false) {
if (count($a) !== count($b)) {
return false;
}
sort($a);
sort($b);
return ($strict && $a === $b) || $a == $b;
}
Here’s another algorithm looking for each element of A if it’s in B:
function array_equal($a, $b, $strict=false) {
if (count($a) !== count($b)) {
return false;
}
foreach ($a as $val) {
$key = array_search($val, $b, $strict);
if ($key === false) {
return false;
}
unset($b[$key]);
}
return true;
}
But that has a complexity of O(n^2). So you better use the sorting method.
The array_diff() method above won't work.
php.net's manual says that array_diff() does this:
"Returns an array containing all the entries from array1 that are not present in any of the other arrays."
So the actual array_diff() method would be:
function array_equal($array1, $array2)
{
$diff1 = array_diff($array1, $array2);
$diff2 = array_diff($array2, $array1);
return
(
(count($diff1) === 0) &&
(count($diff2) === 0)
);
}
However I go with the sort method :D
You can use array_diff.
$a = array('4','5','2');
$b = array('2','4','5');
if(count(array_diff($a, $b)) == 0) {
// arrays contain the same elements
} else {
// arrays contain different elements
}
However, a problem with this approach is that arrays can contain duplicate elements, and still match.
You can use array_intersect() instead of array_diff():
$a = array('4','5','2');
$b = array('2','4','5');
$ca = count($a);
$cb = count($b);
$array_equal = ( $ca == $cb && $ca == count(array_intersect($a, $b)) );
Performance wise. solution, where two factors are important:
the more often arrays are matching, the more array_intersect() is fast.
the more arrays are big (more than 10 values), the more array_intersect() is fast.
Depending on these factors, one method can be two or three time faster than the other. For big arrays with few (or no) matching combinations, or for little arrays with lots of matching, both methods are equivalent.
However, the sort method is always faster, except in the case with little arrays with few or no matching combinations. In this case the array_diff() method is 30% faster.
You only need to compare one-way using array_diff() and use count() for the inverted relationship.
if (count($a1) == count($a2) && !array_diff($a1, $a2)) {
// equal arrays
}
If the arrays being compared consist of only strings and/or integers, array_count_values allows you to compare the arrays quickly (in O(n) time vs O(n log n) for sorting) by verifying that both arrays contain the same values and that each value occurs the same # of times in both arrays.
if(array_count_values($a1) == array_count_values($a2)) {
//arrays are equal
}
As an addition to the accepted reply from #knittl
To cover the case, when one of the arrays has additional members:
function areEqualIfOrderIgnored(array $a1, array $a2): bool
{
if (
! array_diff($a1, $a2)
&& ! array_diff($a2, $a1)
&& count($a1) === count($a2)
) {
return true;
}
return false;
}
Or one line, as requested (but not nice)
if (! array_diff($a1, $a2) && ! array_diff($a2, $a1) && count($a1) === count($a2)) {do smth}