Use if inside foreach

Asked

Viewed 7,269 times

5

I’m trying to change the order in which the results appear within a loop using foreach. What I need is for the numbers larger than five to appear first, followed by the rest of the numbers. So I tried something like this:

$numeros = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo '<ul>';
foreach($numeros as $numero){
    if($numero > 5){
        echo '<li>'.$numero.'</li>';
    }else{
        echo '<li>'.$numero.'</li>';
    }
}
echo '</ul>';

But it’s not working.

  • 3

    You are printing the same thing whether it is bigger q 5 or not

5 answers

16


I answered only to illustrate what is happening. What happens in your code, is that you have created a condition that can be read like this:

  1. Itere in all elements
  2. If larger than five, print.
  3. otherwise, print.

Then they all appear. Try this code, with the same problem, but with a "hint" inside the if to understand what happened:

$numeros = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo '<ul>';
foreach($numeros as $numero){
    if($numero > 5){
        echo '<li>MAIOR QUE CINCO - '.$numero.'</li>';
    }else{
        echo '<li>MENOR OU IGUAL - '.$numero.'</li>';
    }
}
echo '</ul>';

A simplistic solution would be to separate the loops (still didactically, because in the practical case, we would probably have much better solutions):

$numeros = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
echo '<ul>';
foreach($numeros as $numero){
    if($numero > 5){
        echo '<li>'.$numero.'</li>';
    }
}
foreach($numeros as $numero){
    if($numero <= 5) {
        echo '<li>'.$numero.'</li>';
    }
}
echo '</ul>';

We stay that way:

  1. Itere in all elements
  2. If larger than five, print.
  3. Itere in all elements AGAIN
  4. Only if it is less than or equal to five, print.

This is a didactic response. In the practical case, several optimizations could be made, depending on the use of the data.

  • I was going to post this now, but as it is already there that stay your, ^^

  • @Bacco I thought that if the first condition was not satisfied, he would skip to the second.

  • 1

    This was a logical mistake , because as a foreach goes through all the items of a array, With each item it will check if it is bigger q 5 and print, if it is not bigger q 5 it prints the same way. That’s what your code was doing. That’s why it was necessary to do 2 foreach, for each to make a different check.

  • 1

    I updated the response with a second code, which illustrates what happened. Your if works, but the logic is not suitable for the desired result.

  • I think an orderly solution would be better, no?

  • 1

    @Erloncharles Happens :) ... But it’s worse when we put on and someone 5 seconds before posted the same thing and we didn’t see it in time.

  • @Felipeavelar depends a lot on what he wants to do, I don’t know exactly what he wants, it would be interesting if marcelo2605 explained exactly what he wants, so we could optimize his solution.

Show 2 more comments

3

You can also treat the arrays before printing, as follows:

$numeros = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
asort($numeros); // necessário se o array estiver desordenado
$num = 5; // valor limite
$pos = array_search($num,$numeros); // pega a posição do array conforme valor determinado
$numerosMenores = array_slice($numeros,0,$pos); // pega parte do array com os numeros menores
$numerosMaiores = array_slice($numeros,$pos); // pega parte do array com os numeros maiores
$numeros = array_merge($numerosMaiores, $numerosMenores); //funde os arrays

foreach($numeros as $numero){
    echo '<li>'.$numero.'</li>';
}
echo '</ul>';

OBS: If your array is out of order you will first need to order it, asort($numero), or this won’t work.

2

Although with PHP you can do many things in many different ways it doesn’t mean you will hammer a bolt just because you haven’t found the right key.

With that in mind, analyze what you want to do: "A condition within an iteration". What will that condition do? " It will filter a certain result before performing the routine on it".

So use the right or most appropriate tool for the task at hand: array_filter()

This function will receive a given input array and filter it according to the function passed as the second argument. This function can be a string for some function known to the program (such as a native function, for example), an anonymous function, or even an object method.

$data = array( 1,2,3,4,5,6,7,8,9,10 );

$data = array_filter(

    $data,

    function( $current ) {

        return ( $current <= 5 );
    }
);

$date, now has only five elements, from one to five.

"But I have to print everything"

Here is where the various possibilities come in. A cool thing would be to compute the difference of the input array for this filtered, with array_diff()

"But still I’ll have to iterate to print"

Only if you want to. Because a one-dimensional matrix can perfectly be printed with implode(), with HTML and everything:

$data = array( 1,2,3,4,5,6,7,8,9,10 );

$lowerThanFive = array_filter(

    $data,

    function( $current ) {

        return ( $current <= 5 );
    }
);

printf(

    "<ul>\n    <li>%s</li>\n</ul>",

    implode( "</li>\n    <li>", $lowerThanFive )
);

printf(

    "\n\n<ul>\n    <li>%s</li>\n</ul>",

    implode( "</li>\n    <li>", array_diff( $data, $lowerThanFive ) )
);

Note that, because this is an example, I created two distinct, unordered lists, mainly to demonstrate that it works.

1

Instead of displaying inside the foreach, store these values within a string and when you finish the look print the biggest $and then the lowest $

$numeros = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$maiores='';
$menores='';
echo '<ul>';
foreach($numeros as $numero){
if($numero > 5){
    $maiores.= '<li>'.$numero.'</li>';
}else{
    $menores.= '<li>'.$numero.'</li>';
  }
}
echo $maiores;
echo $menores;
echo '</ul>';

0

A simpler way to solve this, taking into account that the important thing is to select from the largest to the smallest and gain performance:

$numeros = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
rsort($numeros);

foreach($numeros as $numeroSelecionado)
{
    echo $numeroSelecionado.'<br/>';
}
  • Who negatived, could explain the reason?

  • Perhaps those who have done this did not understand their point of view that, although correct, in the real scenario that not the original presented may not function as intended because everything indicates that the array in question cannot have its ordered structure but only presented differently.

  • I agree, but since all the examples are based on the proposed original array, this becomes a paradox of who has negatively. Irresponsibly negative is against the rules, and in case of doubt about the method I used it was enough that he just commented and drew it to reach a fair conclusion. But, life that follows rsrs

  • It is, but whatever it was preferred to spend his own reputation to negativar without thinking first. You will understand...

Browser other questions tagged

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