1

I am trying to write a function that takes an array and removes the duplicates, returning the result as a comma separated string. After some Googling, I found its possible to do itwith a single line ( return implode(",",unique_array($arr)); ). However, that doesn't help me figure out was wrong with my original code. So perhaps you could tell me the logical errors in my original code that causes it to return all the values, including the duplicates?

Thank you! :-)

<?php

function GetUniqueValues($arr) {
  $x=0;
  foreach($arr as $i) {
    if(!in_array($i, $arr2)) {
      $arr2[x]=$i;
      $x++;
    }
  }

  $str = implode(",",$arr);

  return $str;
}


$arr = array(1,2,2,3,2,4,4,5,4,7,6,8,9);

echo GetUniqueValues($arr);

?>
4

2 回答 2

0

$arr2[x]=$i;应该是$arr2[$x]=$i;(缺失$

打开错误报告并将其设置为报告所有错误和通知。PHP 会告诉你这些错误。

ini_set('display_errors', 1); 
error_reporting(E_ALL);
于 2013-04-17T16:48:59.140 回答
0
  $arr2[x]=$i;

这是错误的。你错过了一个$- 标志。应该:

  $arr2[$x]=$i;

顺便提一句。你也可以这样做:

  $arr2[]=$i;
于 2013-04-17T16:49:16.527 回答