Home > Back-end >  Where is the wrong in this foreach?
Where is the wrong in this foreach?

Time:10-01

In the following structure:

$numbers = array("one", "two", "three", "four"); 

foreach ($numbers as $value) {
    if( $value == 'two' ) { 
        echo '$value <br>';
    }
    else {
        echo 'This numbers doesnt exist in the array';
    }
}

I intend that if one of the if values is equal to two (in this case one of the values is equal to 2), I print the entire array, that is, one, two, three, and four, and for example, if I put that the if is equal to 5, since that value does not exist in the array, it is entered through the else. From the code I have provided, what have I done wrong?

CodePudding user response:

The way your code works currently, you are iterating through each value in the array. If the value you are up to is the sentinel value (in this case the string "two") then you are printing it, otherwise you are printing another message.

If you wish to print the entire array if and only if it contains the sentinel value, you can use in_array() to check for the existence of the sentinel value first:

$sentinel = 'two';
if ( in_array($sentinel, $numbers ) ) {
  foreach ( $numbers as $number ) {
    echo "$number<br>";
  }
} else {
  echo "The number $sentinel does not exist in the array.";
}
  •  Tags:  
  • php
  • Related