Jump to content

Using 'for loop' through an array after removing duplicates with array_unique


meneimoh

Recommended Posts

I had an array with duplicates. I removed the duplicates using PHP array_unique function. Then, I loop through the unique array using for loop (Sample Code below) and , I got an Undefined offset error. 


$even_numbers = array(22,66,24,22,36);
$unique_even_numbers = array_unique($even_numbers);

for($i=0; $i<count($unique_even_numbers); $i++){
  echo $unique_even_numbers[$i].'<br>';
}

The interesting thing is that I  forgot I removed duplicates from the array somewhere (and therefore, an index). It took me something to figure out what was happening.  I then used foreach. If I'm not missing something then I think it will be helpful if this is mentioned somewhere in the w3schools tutorial.  It may help especially beginners. 

original array.PNG

unique array.PNG

Offset Error.PNG

Link to comment
Share on other sites

The reason is that the keys haven't changed. You should use a foreach() loop where possible to iterate through arrays. I rarely ever use a for loop.

If you would like to reassign the indices after the call to array_unique(), you can use array_values(). Then you can use a classic for() loop.

$unique_even_numbers = array_values(array_unique($even_numbers));

 

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...