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!
That can't be done because a foreach block returns nothing.
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.
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.
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 .
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) {
// ...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With