Eyang Makmur Eyang Makmur - 1 month ago 5
PHP Question

How to skip foreach if same value?

I have loop value with code

foreach($season as $seasons){
echo $seasons->Combined_season ;
}


and the result is 0000000011111111111111111111111222222222222222222222223333333333333333333333344444444444444444444444555555555

How to skip if there same values?
I want the result is
012345

Answer

You are looking for "unique" values:

<?php
foreach($season  as $seasons){  
    $result[] = $seasons->Combined_season;
} 
echo implode('', array_unique($result));

A somewhat awkward but more memory efficient version would be this:

<?php
foreach($season  as $seasons){  
    $result[$seasons->Combined_season] = $seasons->Combined_season;
} 
echo implode('', $result);

And the most efficient variant:

<?php
foreach($season  as $seasons){  
    $result[$seasons->Combined_season] = null;
} 
echo implode('', array_keys($result));

All approaches have the advantage that they do not require a conditional in each loop iteration which makes them far more efficient for bigger input sets.


Here an update to answer your additional question:

I mentioned more than once in my comments that the variant 2 and 3 deliver what you are looking for. That you only have to use the values internally instead of imploding them for output.

The following is exactly the third approach from above, the only difference is that I did what I told you before in the comments: use the values instead of imploding them. As far as I can see it delivers exactly what you are looking for:

<?php
foreach($season  as $seasons){  
    $result[$seasons->Combined_season] = null;
} 
$value = array_keys($result);
Comments