I have this little snippet here, and it returns false
even if it satisfies the if
statement.
$urls = $_POST['links'];
trim($urls);
$urls = explode("
",$urls);
foreach($urls as $url){
trim($url);
if(strpos($url,'http://') === false)
$url = 'http://'.$url;
$parse = parse_url($url, PHP_URL_HOST);
if(($parse != 'site.com') || ($parse != 'www.site.com')) //problem here
echo 'false:'.$parse.'<br>';
else
echo 'true:'.$parse;
}
The input is from a textarea:
http://site.com
site.com
http://www.site.com
www.site.com
Output:
true:site.com
true:site.com
false:www.site.com
false:www.site.com
What do you think is the problem?
I'm not sure what you really intended, but the following line is definitely wrong:
if(($parse != 'site.com') || ($parse != 'www.site.com')) //problem here
This will always return true, because it's true if parse is not 'site.com' but it's also true if parse is not 'www.site.com' and since it can't be both of them at the same time, it must always be true. Did you mean && instead of ||? I.e., logical AND instead of logical OR?
if(($parse != 'site.com') && ($parse != 'www.site.com'))
EDIT: Actually, if what you've put in your question is desired behaviour, i.e., true for site.com and false for www.site.com, then you just want:
if ($parse == 'site.com')
{
echo 'false:'.$parse;
}
else if ($parse == 'www.site.com')
{
echo 'false:'.$parse;
}
Or maybe that's not really what you want...
Think about the logic you used in the second if statement. No matter what $parse
is, you will always fall into the if
branch. (That is, you will never fall into the else
branch.)
Consider the following alternatives:
// "Not A AND Not B"
if(($parse != 'site.com') && ($parse != 'www.site.com'))
// ...
// "Neither A nor B"
if(!(($parse == 'site.com') || ($parse == 'www.site.com')))
// ...
// "Either A or B"
if(($parse == 'site.com') || ($parse == 'www.site.com'))
echo 'true:'.$parse;
else
echo 'false:'.$parse.'<br>';
// Note here we also swapped the two branches.
Change the if line to:
if(($parse != 'site.com') && ($parse != 'www.site.com'))
replace this line :
if(($parse != 'site.com') && ($parse != 'www.site.com'))