Question:
PHP trouble with IF/Else logic and variables?
Justin
2013-06-27 22:07:55 UTC
So, I have a couple of variables in PHP, and they are generated from different places. $new_ip comes from the following command:

$new_ip = file_get_contents('http://www.ipaddresscheck.comlu.com/ip.php');


And the $old_ip comes from:

$sql = mysql_query('SELECT * FROM ip ORDER BY id DESC LIMIT 1');
$row = mysql_fetch_array( $sql );
$old_ip = $row['current_ip'];

My problem is, I am getting incorrect results from:

if ($old = $new)
{
$different = '1';
}
else {
$different = '2';
}
echo $different;

I ALWAYS get 2, wether the IPs are the same or not; if I use '==' as the comparison, I ALWAYS get 1.

When I run the following code, I get the following output:
var_dump($old_ip);
var_dump($new_ip);

Output

string(15) "123.123.123.123" string(167) "184.6.216.163 "


Are the variables different types? If So, can I make them the same so I am only comparing the IP and not the type? If the IPs are the same I should get '1' and if they are different, I should get '2', right?
Four answers:
anonymous
2013-06-27 22:58:24 UTC
Your condition is wrong. for TWO reasons:



1) you need to use == or ===, not =. The latter is only used for assignment, so what you're donig is assigning $new to $old. The 'result' of the assignment is equal to $new. So if you ALWAYS get 2, like you sad, then that's because $new is a falsy value. And this is because:

2) you assign the contents of your file to $new_ip, and the result of your query to $old_ip. Therefore, $new and $old (note the absence of _ip!!!) are null; null is a falsy value, hence the output you're getting...
anonymous
2013-06-28 05:14:41 UTC
Current your middle block of code is using the assignment operator in the compare statement. You do have to use the == operator to compare.



I guess you just keep getting different strings for $old and $new when you are testing it with the compare operator.
potatocouch
2013-06-28 07:29:51 UTC
note how the dump for the 184 address has a space at the end. i highly recommend using trim to clean up the ips before any comparing. you might even go as far as using explode on the dot (.) to separate the four octets and compare each octet.
?
2013-06-28 07:10:08 UTC
You use the wrong variables ($new <> $new_ip, $old <> $old_ip=, and the wrong operator sign ("=" <> "==")



==> if ($old_ip == $new_ip)

will solve your problem.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...