0

I have a foreach loop and I need to add a continue if the value has already been echoed. I can't find the right syntax. The loop:

foreach ($results as $result) {
   echo $result->date . "<br />"; 
}

But I need to add in a continue so that if the value has already been echoed, and it comes up again in the loop it gets skipped. I can't quite get the if/continue statement quite right.

Thoughts, suggestions, ideas?

BradM
  • 646
  • 8
  • 18

3 Answers3

5

As mentioned by @JonathanKuhn in the comments - here is how you would run that loop:

$already_echoed = array();
foreach ($results as $result) {
    if (!in_array($result->date, $already_echoed)) { //check if current date is in the already_echoed array
        echo $result->date . "<br />";   
    }
    $already_echoed[] = $result->date; //store all dates in an array to check against.
}
Dan
  • 9,391
  • 5
  • 41
  • 73
  • Either you forgot to echo the date or implode and echo the array. – Charlotte Dunois Sep 18 '14 at 21:22
  • Off topic, is `$array[] = $adding_item` the preferred method of adding to an array? I always use `array_push()`. – tatorface Sep 18 '14 at 21:37
  • 1
    @tatorface `$array[]` preferred - see reference http://stackoverflow.com/questions/1074059/array-push-vs-array-which-is-fastest – Dan Sep 18 '14 at 21:39
  • Instead of posting the code here edit your question - it's too difficult to make sense of it in the comment. – Dan Sep 18 '14 at 21:45
  • You could try adding `array_unique`: `$dateArr = array_unique(explode('-', $result->date));` which will strip duplicates from the array. Otherwise it's a bit tough to provide a good answer without seeing the actual data. – Dan Sep 18 '14 at 21:51
  • @BradM my answer should work as is if you just swap out `$already_echoed[] = $result->date;` and replace it with `$already_echoed[] = $dateArr[0];`. – Dan Sep 18 '14 at 21:59
  • Thanks for your help - got it configured. :) – BradM Sep 18 '14 at 22:13
  • 1
    @Dan thanks, I did the test on your linked page and it $array[] is by far and away the quicker tool. Thanks for your help. – tatorface Sep 18 '14 at 22:46
  • @Dan I'm sorry, but I find your example completely wrong. Here is performance I was talking about http://3v4l.org/Anq56 – Tengiz Sep 19 '14 at 16:01
2
$echoedArray = array();
foreach ($results as $result) {
    if (isset($echoedArray[$result->date])) {
        continue;
    }
    echo $result->date . "<br />";
    $echoedArray[$result->date] = true;
}
Tengiz
  • 1,902
  • 14
  • 12
1
    $alreadyOutput = array();
    foreach ($results as $result) {
       if(in_array($result->date, $alreadyOutput)){
           continue;
       }
       $alreadyOutput[] = $result->date; 
       echo $result->date . "<br />";
    }
Ahamad I Milazi
  • 479
  • 3
  • 14