0

I want to use unique array in for loop. Please see my code.

Array ( [0] => Pritesh [1] => Pritesh [2] => Nilesh )

Now i have used "UNIQUE" function for fetch unique value

 Array ( [0] => Pritesh [2] => Nilesh ) 

But Now issue is when i use for loop for that like

for($p = 0; $p < count($unique); $p++)
    {   echo $uniques;
        echo  '<option value="'.$unique[$p].'">'.$unique[$p].'</option>';
    }   

So second value showing blank because array count is 2 and Key is 0,2 .

How i use this.

2
  • 2
    Use foreach instead of for Commented Dec 19, 2013 at 7:16
  • Can't help wondering how did you get these non-unique values. Commented Dec 19, 2013 at 7:17

6 Answers 6

4

Do like this before you pass into the loop..

$yourarray = array_values(array_unique($repeated_values_array));

Now make use of $yourarray in the for loop.

Sign up to request clarification or add additional context in comments.

4 Comments

array_values returns yet another array. This code may be a one-liner, but it takes an array, creates a new, unique-values-only array,and then creates a third array with only the unique values. sort resets the array's keys without creating the unique array anew.
Sorting is not the right thing to do. What if the values are to be maintained in the same position ?
If that is the case, sorting isn't right, true (unless you use usort with function keepOrder($a, $b) { return 0; }, but that's silly). In this case, OP didn't mention he cared about the order, so I didn't assume the order of elements was relevant.
I've made some edits to my answer, suggesting your answer if OP wants to guarantee key-integrity and not to change the order of elements in the array. I've also added some silly solutions, for fun
2
foreach($uniques as $key => $unique) {
  echo '<option value="'.$unique.'">'.$unique.'</option>';
}

As stated in the comment, you do not need to assign a variable for the key, if you don't need it. (I just used is as a handy reference). So you can simply do this:

foreach($uniques as $unique) {
  echo '<option value="'.$unique.'">'.$unique.'</option>';
}

3 Comments

why bother foreach($uniques as $key => $unique), assigning 2 variables on each iteration, if you're not going to use $key? foreach($uniques as $unique) is shorter to write, marginally faster and iterates only of that which you need: the values
I thought it would be a good idea to include the key variable, as OP probably did not know about this syntax. Performance is not the issue here. But you're certainly right. I've edited my answer to include both constructs.
Now, since I'm on a pedantic-streak: the most efficient echo doesn't concatenate strings, it comma-separates them. I've given a lengthy explanation on the matter here
2

Please, read the manual. array_unique doesn't reset the array keys. Besides, a for loop is all well and good, but foreach is a language construct better suited to deal with arrays (and objects, for that matter).
That said, the fastest way to reset the array keys after array_unique has been applied is to sort the array:

$a = array( 'Pritesh','Pritesh','Nilesh' );
$b = array_unique($a);
sort($b);
var_dump($b);

This results in:

array(2) {
  [0]=>
  string(6) "Nilesh"
  [1]=>
  string(7) "Pritesh"
}

Which is suitable for both for and foreach.

Edit:
As is often the case in programming TMTOWTDI (There's more than one way to do it). Here's a couple of approaches, ranging from valid to absurd:

Quick:

foreach($uniques as $unique) echo '<option value="', $unique, '">', $unique,'</option>';

Yes those are comma's, comma's + echo is actually faster (~20-30%) than concatenation
When to use: whenever you feel like it, it doesn't change the $uniques array (so it's still inconcistently indexed), but it's quick and easy to read.

Fix $uniques indexing:

sort($uniques);
foreach($uniques as $unique) echo '';//same deal

The difference with the previous version is that you can replace foreach with for here, too, and that the $uniques array will be properly indexed again. The order of the elements may have changed.
If the order of the elements is important, and you want a neatly indexed array, use:

$uniques = array_values($uniques);//as Shankar Damodaran suggested

Use when your use-case fits the very specific and unlikely scenario described above.
or, and things are getting absurd from here on end:

function keepOrder($a, $b)
{
    return 0;
}
usort($uniques, 'keepOrder);

Use: never

Since we are taking it rather far in terms of over-engineering a solution, let's take it to the extend where the solution becomes a problem all over again (Warning, the following code may cause your eyes to bleed):

//get the highest key in array, add 1
$max = max(array_keys($uniques)) + 1;
for($i=0;$i<$max;++$i) if (isset($uniques[$i])) echo $unique;

I've deliberately made the code above harder to read, to avoid anyone using it.
When to use: use when you are either clinically insane, or want to see a co-worker being taken away in a straitjacket, shouting "The horror, the horror".
Seriously: don't use it.

Comments

1

Use the foreach function of PHP

 foreach($unique as $val)
 {   
      echo $val;
      echo  '<option value="'.$val.'">'.$val.'</option>';
 }  

Comments

1

Use foreach instead of for loop

if you need your key as well, do this:

foreach ($unique as $key=>$value)

where $key will be the array key.

Comments

0

It seems that what you need is called "rebase array keys". As discussed in this post: Rebase array keys

So use

$array = array_values($array);

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.