Reputation: 1
I want a PHP program to tell if an array contains any equal data. For that I'm writing this code but it always returns false, even though I have given equal values at position array position 1 and 2. Can anyone help me find out what is wrong with this code?
$a[0]=qwe;
$a[1]=abc;
$a[2]=abc;
$a[3]=xyz;
if(is_equal($a))
{
echo "True";
}
else
{
echo "False";
}
function is_equal($a)
{
$size=sizeof($a);
for ($i = 0; $i <= $size-2; $i++)
{
if ($a[i] === $a[i+1])
{
return true;
}
}
return false;
}
Upvotes: 0
Views: 86
Reputation: 212412
The problem with your existing code is that
if ($a[i] === $a[i+1])
should be
if ($a[$i] === $a[$i+1])
PHP variables start with a $
, otherwise i
is treated as a constant, and as the constant isn't defined, then a string value of "i"
$a["i"]
doesn't exist, therefore it can never be equal to anything; and $a[i+1]
will add 1 to i
giving 1, so it is always a comparison of a non-existent array element against element 1
Upvotes: 2
Reputation: 91734
You don't need to write a function for that, you can use array_unique
:
if ($array !== array_unique($array))
{
// There were duplicate values
}
Upvotes: 5