Jump to content

unique array


babaz

Recommended Posts

ok so i have an array which has duplicate values in it.

 

i used array_unique() to remove duplicate values.

 

the array had values 1,2,2,3.

 

after the following code:

 

$unique = array_unique($suggest);
$size = count($unique);
for ($x=0;$x<=$size;$x++)
{

     echo $unique[$x];
echo "<br>";
				}

 

it prints out 1,2 and then gives an error, "Notice: Undefined offset: 2 in E:\wamp\www\Copy of pro2\Classes.php on line 1074" and then finally 3.

 

any ideas  how i can solve this.

 

im assuming that array_unique() assigns the index 0,1,3 of the duplicate value array to unique array at the same indexs 0,1,3. since the index 2 of duplicate array is a duplicate value it is ommited but the unique array does not have an array at index 2.

Link to comment
Share on other sites

as an exaple try running this code and see wot happens:

<?php

$dirty = array('danish','mukesh','braden1','shadab','bev','braden1','kirsten','john');

 

$clean = array_unique($dirty);

 

for($i=0; $i<count($clean); $i++)

    {

        echo $clean[$i] . "<br />";

    }

?>

Link to comment
Share on other sites

thanks....dat helped! also tried

 

for ($x=0;$x<$size;$x++)
			{
				if(isset($unique[$x]))
				{
				echo $unique[$x];
				echo "<br>";
				}
				}

 

and worked fine....

 

Yeah, but that is still a flawed solution. The problem is that your original array looks like this

array (
    0 -> 1,
    1 -> 2,
    2 -> 2,
    3 -> 3
)

 

After using array_unique() you are left with

array (
    0 -> 1,
    1 -> 2,
    3 -> 3
)

... because  the keys are preserved. Therefor there is no element with an index of 2. You can either reset the array indexes as requinix proposed. But, there is an even easier solution - DON'T USE A FOR LOOP. All you want to do is iterate through each element in an array. So, just use foreach() - that's what it is for.

 

$unique = array_unique($suggest);
foreach($unique as $value)
{
    echo "{$value}<br>\n";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.