Using Else inside the foreach

Asked

Viewed 318 times

1

Guys 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 Else echo goes into action the result is this:

Nada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada encontradoNada....

The ideal is to appear only once the Nada encontrado.

  • Try to put ; after the last }, and put a break after each return (from if and of else)... In the case of else stays else { echo "Nada encontrado"; break; }

  • You can put an example of what you would have $results['results']['collection1']?

1 answer

2

From what I understand, if, at least once, the content of if is true, the "Nada encontrado" should not appear. Create a variable to control this and test if you found something outside 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";
  }

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.