Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing a foreach loop inside an if condition

I am needing to create a foreach statement that will run through and create conditions for a conditional statement. I wrote this bit of code, not expecting it to work, and of course it didn't...

$filename = "whitelist.txt";
$handle = fopen($filename, 'r');
$whitelist = fread($handle, filesize($filename));
fclose($handle);
$whitelist = explode("\n", $whitelist);
if (
  foreach ($whitelist as $value) {
    strpos($ref, 'http://'.$value.'/')===0 ||
  }
)

So, should this ever be able to work? Or am I just crazy? If there is really no way to put a loop in the condition like this, could someone suggest a better way to do this? Much appreciated!

like image 1000
Ben Kulbertis Avatar asked Aug 28 '10 15:08

Ben Kulbertis


People also ask

Can we use forEach in if condition?

That can't be done because a foreach block returns nothing.

Can we Write for loop inside if condition?

You can put a for loop inside an if statement using a technique called a nested control flow. This is the process of putting a control statement inside of another control statement to execute an action. You can put an if statements inside for loops.

How to break inside forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Can we use forEach inside forEach?

Due to operator precedence, you cannot put braces around the inner foreach loop. This is structured very much like the nested for loop. The outer foreach is iterating over the values in bvec , passing them to the inner foreach , which iterates over the values in avec for each value of bvec .


2 Answers

Compute the value beforehand, you cannot use a loop as an expression:

$val = false;

foreach ($whitelist) {
   $val = $val || strpos($ref, 'http://'.$whitelist.'/')===0;
}

if($val) {
    // ...
}
like image 100
Felix Kling Avatar answered Sep 20 '22 22:09

Felix Kling


You have to invert the two statements and put the if inside the for loop. Loop over the whitelist, and once you find a match set a flag and exit the loop using break. Then check that flag after the loop and see if it ever got set.

$allowed = false;

foreach ($whitelist as $url) {
    if (strpos($ref, "http://$url/") === 0) {
        $allowed = true;
        break;
    }
}

if ($allowed) {
    // Do what you want to do.
}

For what it's worth, there are other more expressive languages where you could write the code the way you tried to. In python, for instance, you could write this:

if any(ref.starts_with('http://'+url+'/') for url in whitelist):
    # Found a whitelisted URL.
like image 25
John Kugelman Avatar answered Sep 19 '22 22:09

John Kugelman