0

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;   
}  
3
  • 1
    The number of items in the array is count($a), not sizeof($a), I think. Are you not missing some quotes in the first four lines? Commented Nov 26, 2013 at 14:51
  • 2
    @CompuChip Have you read the manual? sizeof is an alias of count ;) Commented Nov 26, 2013 at 14:52
  • Apparently not :) Thanks @kingkero! Commented Nov 26, 2013 at 15:13

2 Answers 2

5

You don't need to write a function for that, you can use array_unique:

if ($array !== array_unique($array))
{
  // There were duplicate values
}
Sign up to request clarification or add additional context in comments.

4 Comments

True but what if the goal is to identify unique or non-unique values ? Or, as the code might indicate, to identify consecutive identical values, ignoring them if they're not consecutive... From where I see it array_unique() is to PHP what distinct is to SQL
@Bartdude There are other built-in array functions to get for example the difference if the OP should need that. From how I read the question, this is all the OP needs, but it could always be adapted according to the exact specifications.
can u plz elaborate it, actually i m new to php
@user3036851 There is not much more to it, if you want you can replace the contents of your whole function with return ($a !== array_unique($a)); and that is about it.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.