Using else inside foreach

1

Personal I have the following code:

<?php 
  $string = $_POST['search'];
  foreach($results['results']['collection1'] as $collection) {
    if(stristr($collection['prod']['text'],$string) !== false) {
      echo "<div class='col-lg-4 col-sm-6'><img src='" . $collection['img']['src'] . "'><br />"; 
      echo "<a target='_blank' href='" . $collection['prod']['href'] . "'>" . $collection['prod']['text'] . "</a><br />". $collection['valor'] . "</div>";
    } else {
        echo "Nada encontrado";
    }
  }

The problem that when the echo of the else goes into action the result is this:

  

asked by anonymous 02.08.2015 / 19:45

1 answer

2

As I understand it, if, at least once, the content of if is true, "Nada encontrado" should not appear. Create a variable to control this and test if it found something out of the loop:

<?php 
  $string = $_POST['search'];
  $encontrado = false;
  foreach($results['results']['collection1'] as $collection) {
    if(stristr($collection['prod']['text'],$string) !== false) {
      echo "<div class='col-lg-4 col-sm-6'><img src='" . $collection['img']['src'] . "'><br />"; 
      echo "<a target='_blank' href='" . $collection['prod']['href'] . "'>" . $collection['prod']['text'] . "</a><br />". $collection['valor'] . "</div>";
      $encontrado = true;
    }
  }
  if (!$encontrado) {
    echo "Nada encontrado";
  }

In this way only if nothing is found, the text will be displayed only once.

    
02.08.2015 / 21:38