3061LRTAGSPKJMORMRT
3061LRTAGSPKJMORMRT

Reputation: 108

Having problems when removing duplicates

So I am trying to remove duplicates from an array. The array is made from strings.

$string = "B+,A,A,A+,C,B,B,";
$okay = explode(",", $string);
array_pop($okay);
$newarray = array_unique($okay); 
for ($x = 0 ; $x < count($newarray) ; $x++) {
  echo $newarray[$x];
}

However, when I try to run it, for some reason, it says the following:

Warning: Undefined array key 2 in Standard input code on line 14

I do not know what is causing this. I think that array_unique just removes that element at that space, hence $newarray[2] is undefined. If so, are there any ways that I can use to display the new array properly?

Upvotes: 0

Views: 31

Answers (1)

KIKO Software
KIKO Software

Reputation: 16751

Instead of using:

for ($x = 0 ; $x < count($newarray) ; $x++) {
  echo $newarray[$x];
}

you could use:

foreach ($newarray as $value) {
  echo $value.'<br>';
}

circumventing the problem with the keys completely.

If you want to show the keys as well you could do:

foreach ($newarray as $key => $value) {
  echo "$key = $value<br>";
}

Upvotes: 1

Related Questions