0

Following is my code:

$array1=('23','3','55','67');
function has_dupes($array1){
 $dupe_array = array();
 foreach($array1 as $val){
  if(++$dupe_array[$val] > 1){
   return true;
  }
 }
 return false;
}

I'm new to PHP and wanted to write a function to check an array for duplicate integers. My code is below:

It gives an error: Parse error: syntax error, unexpected ',' on line 1

2

8 Answers 8

3

you missed array keyword

$array1 = array('23','3','55','67');
         ^ // here was the mistake
Sign up to request clarification or add additional context in comments.

Comments

3
function has_duplicates($myArray) {
    return (max(array_count_values($myArray)) > 1);
}

Comments

2

Your immediate problem is that you are using the wrong array syntax. Correct would either be

$array1 = ['23','3','55','67']; // only possible in PHP >= 5.4

or

$array1 = array('23','3','55','67'); // all versions of PHP

Regarding the dupe detection function, you don't need one because there is a ready-made one you can use: array_unique.

if (count(array_unique($array)) != count($array)) {
    // the array has dupes
}

2 Comments

@j0k: Well, it's been out for almost a year now. I added a comment to clarify anyway.
I know, sadly PHP 5.4 isn't really used in comparison to PHP 5.3.
1

You can use array_unique to perform this check easily. Just compare length of original array against the length of the unique version of the array.

function has_dupes($array){
  return count($array) != count(array_unique($array));
}

Also you want to declare an array using array().

Comments

1
$array1= array(23,3,55,67);

Thread integers as integers.

Comments

1

By putting the numbers in quotes, you're treating them as string. Also, the array syntax is wrong...

$array1 = array(1,2,25,26);

Comments

1

This is the error

$array1=array('23','3','55','67');

Comments

1

Why don't you just do this?

$array1 = array_unique($array1)

Have I misinterpreted the question?

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.