Something wrong with my second else statement? - php

<?php
$check = array ("85.49.","85.62.");
foreach($check as $var) {
if (ereg($var, $_SERVER['REMOTE_ADDR'])) {
$intruder = 0;
}
else {
$intruder = 1;
}
if ($intruder = 0);
echo 'bugger off';
}
else{
echo 'welcome';
}
?>
What could be wrong with my second else? Dreamweaver red flags it and my server says error. All I want to do is get it to behave one way or another if $intruder is 1 or 0.

if ($intruder = 0);
First, you have an extra semicolon, so the body of the if statement is empty.
Secondly, = is assignment, you need comparison: ==.
The structure is not clear, but probably the next problem is your loop, which will overwrite $intruder in each iteration, so at the end it will contain the result of the last comparison.

The problem you ask about is on this line:
if ($intruder = 0);
You should be using == to compare the values, not = which is for assignment. And you should have a curly brace { after that instead of a semicolon.
Also, all of the ereg* functions are deprecated and should not be used. They will eventually be removed from the language entirely. To check if a word contains another word, just use strpos.
Your logic is also wrong for what you appear to be doing. You need to not overwrite the values of $intruder in each iteration of the loop. Set it to 0 before the loop, set it to 1 if there's a match in the loop, then after the loop is complete you'll know if there was a match during any of the comparisons and can print the appropriate message.
$found = 0;
foreach ($check as $var) {
if (strpos($_SERVER['REMOTE_ADDR'], $var) === 0) {
$found= 1;
}
}
if ($found == 1) {
echo "You are in my list.";
} else {
echo "You are not in my list.";
}
?>

Change this:
if ($intruder = 0);
To this:
if ($intruder == 0) {

First error:
if ($intruder = 0);
fix it in this way:
if ($intruder == 0)
echo 'bugger off';
else
echo 'welcome';
Second error:
The use of ereg is deprecated. Replace it with preg_match(); http://www.php.net/manual/en/function.preg-match.php

Friend, please do not be offended, but I'd rather have asked "is there anything right in this code?"
<?php
$check = array ("85.49.","85.62.");
foreach($check as $var) {
// Here you use the deprecated ereg instead of preg_match or, better, strpos
// However, the regular expressions would be wrong - what if 192.85.49.3 comes by?
if (ereg($var, $_SERVER['REMOTE_ADDR'])) {
$intruder = 0;
}
else {
$intruder = 1;
}
// Here you do not close the foreach, so that the following code gets executed
// repeatedly
// Here you place a ; after the if, so the if body is empty and bugger off gets
// triggered always.
// Which changes little, since $intruder = 0 is an assignment (use == instead)
// (see note)
if ($intruder = 0);
echo 'bugger off';
}
// Anyway, logically "$intruder == 0" means "NOT an intruder", so you are actually
// telling friends to bugger off and welcome intruders :-)
else{
echo 'welcome';
}
?>
Note: it is maybe voodoo programming (I found it on Maguire's 'Writing Solid Code'), but I think you might get into the habit of checking values the other way:
if (0 == $intruder)
This way if you ever drop a = again, it will not create a new statement doing something you wouldn't want, but it will become a syntax error that makes itself immediately visible.
Anyway, the code for what you want should be:
<?php
$check = array ("85.49.","85.62.");
$matches = false;
foreach($check as $var)
{
if (0 === strpos($_SERVER['REMOTE_ADDR'], $var))
{
$matches = true;
// There is one match, no sense in checking further
break;
}
}
if ($matches)
{
// He is in our little list - tell him something
print "You match.";
}
?>

Simple yaar.Just edit:
if ($intruder == 0);
echo 'bugger off';
}
else{
echo 'welcome';
}

Related

Loop within loop exit [duplicate]

I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
foreach ($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// Found a match in the file.
$nodeid = $equip->id;
<break out of if and foreach here>
}
}
if is not a loop structure, so you cannot "break out of it".
You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
Just for completeness for others who stumble upon this question looking for an answer..
break takes an optional argument, which defines how many loop structures it should break. Example:
foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['3','2','1'] as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
Resulting output:
1 3 2 1 !
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break. That will do it.
A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here

if condition fails while checking json array values

i have a simple json array. in which i have two objects. now i am checking it for some specific values , if found do some thing , if not found do another thing. But i dont know why if condition runs both blocks. true and false both blocks are executed. please help.
$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring);
$count = count($jsonarr->like);
for ($r = 0; $r < $count; $r++)
{
if ($jsonarr->like[$r]->username == 'abc' && $jsonarr->like[$r]->password == 'abc')
{
echo 'Match';
}else
{
echo 'No Match';
}
}
is it not like regular if condition ?
It's showing both blocks because you are looping thru the json array which contains two items. One matching your condition, the other not matching. Here is a simpler version that does not use a loop but just tests your value if in the array. Notice the 'true' flag in the json_decode as well.
<?php
$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring, true);
$testArray = $jsonarr['like'];
$loginArray = array('username'=>'abc','password'=>'abc');
if (in_array($loginArray,$testArray)) {
echo 'match found, do login';
} else {
echo "no match, do something else";
}
?>

break out of if and foreach

I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
foreach ($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// Found a match in the file.
$nodeid = $equip->id;
<break out of if and foreach here>
}
}
if is not a loop structure, so you cannot "break out of it".
You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
Just for completeness for others who stumble upon this question looking for an answer..
break takes an optional argument, which defines how many loop structures it should break. Example:
foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['3','2','1'] as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
Resulting output:
1 3 2 1 !
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break. That will do it.
A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here

break; vs continue; vs return;

I downloaded a free newsletter written in php from hotscripts.com
I updated a little the code to add new functionality and I saw something I don't understand.
In the code I see:
foreach() { ...
if() ...
break;
elseif() ...
continue;
}
I also saw:
function() {
// ...
for($nl = 0; ...
if() ...
return true;
}
I read that break; will stop the loop, continue will skip the loop to the next iteration and return will exit the function.
What I don't understand is why coding that style? Why not use something like:
function() {
// ...
for($nl = 0; ...
if() ...
$returnValue = true;
else {
$returnValue = false;
}
}
return $returnValue;
}
or same idea in the for loops?
Using keywords such as break and continue can make the code far easier to read than what you propose.
Especially if you are nesting if/else-statements more than one level.
Compare the snippets further down in this post, which one is easier to read?
Both of them output the same exact thing, and $A is array (1,2,4,4,3,4).
A return in a loop (inside a function) can save precious CPU cycles, if you know you don't need to loop any further, why do it?
I'm too cool to use break/continue..
$not_even_found = false;
foreach ($A as $v) {
if ($v != 1) {
if ($not_even_found) {
} else if ($v % 2 != 0) {
$not_even_found = true;
} else {
echo "$v\n";
}
}
}
I want to have readable code..
foreach ($A as $v) {
if ($v == 1)
continue;
if ($v % 2 != 0)
break;
echo "$v\n";
}
You code using that style so that you save unnecessary loops when the first time a condition is met then you already now that something is true and you don't need to investigate further.
In fact if you return you stop the loop. A stupid example
function in_array($needle, $haystack){
for($i = 0; $i < count($haystack); i++){
if($needle === $haystack[$i]{
return $i;
}
}
return -1;
}
in this case when the condition is met you return something (true, or in this case the value of the counter) because you don't need to iterato over the whole array
Some of the "why" comes down to personal preference. Some of it comes down to whether other things need to be done in the same function before it returns. If there's nothing else that needs to be done, and the function is simply supposed to return a true or false answer, then directly using return true; is the most expedient mechanism. If you still need to do some other stuff even after deciding whether to return true or not (close a file handle for example), then assigning the response to a variable and then returning that at the end may be necessary.

Search for a specific string within another string with PHP

I need to search a string for any occurances of another string in PHP. I have some code that I've been playing with, but it doesn't seem to be working.
Here is my code:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos == false) {
echo "allow";
exit;
} else {
echo "deny";
exit;
}
}
I have tried some of the options below, but it still does not find the match. Here is what I'm searching:
I need to find:*
blah
In:
http://blah.com
Nothing seems to find it. The code works in regular sentences:
Today, the weather was very nice.
It will find any word from the sentence, but when it is all together (in a URL) it can't seem to find it.
When checking for boolean FALSE in php, you need to use the === operator. Otherwise, when a string match is found at the 0 index position of a string, your if condition will incorrectly evaluate to true. This is mentioned explicitly in a big red box in the php docs for strpos().
Also, based on a comment you left under another answer, it appears as though you need to remove the exit statement from the block that allows access.
Putting it all together, I imagine your code should look like this:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos === false) { // use === instead of ==
echo "allow";
} else {
echo "deny";
exit;
}
}
Update:
With the new information you've provided, I've rewritten the logic:
function isAllowed($location) {
$keywords = array('blah', 'another-restricted-word', 'yet-another-restricted-word');
foreach($keywords as $keyword) {
if (strpos($location, $keyword) !== FALSE) {
return false;
}
}
return true;
}
$location = 'http://blah.com/';
echo isAllowed($location) ? 'allow' : 'deny';

Categories