$var == 'string1' || 'string2' always returns TRUE - php

I want to echo $q2 and $q3 based on the question parameter, but it keeps giving me the same value regardless of the parameter's value. What did I do wrong?
$q1 = $_GET['question'];
if ($q1 == "domaina.com"||".domaina.com"||"domaina.co")
{
$q2 = 'domaina';
$q3 = 'DomainA';
}
elseif ($q1 == "domainb.com"||".domainb.com"||"domainb.co")
{
$q2 = 'domainb';
$q3 = 'DomainB';
}
elseif ($q1 == "domainc.com"||".domainc.com"||"domainc.co")
{
$q2 = 'domainc';
$q3 = 'DomainC';
}
else {
$q2 = 'noquestions';
$q3 = 'NoQuestions';
}

Any not empty string evaluates to true, so your first 'or' statement always evaluates to true.
The right to do is:
if ($q1 == "domaina.com"||$q1 == ".domaina.com"||$q1 == "domaina.co")
instead of
if ($q1 == "domaina.com"||".domaina.com"||"domaina.co")

tooooo repetitive.
$q1 = $_GET['question'];
$q2 = 'noquestions';
$q3 = 'NoQuestions';
if (preg_match('~^.?domain([a-c])\.com?$~',$q1,$m)) {
$q2 = 'domain'.$m[1];
$q3 = 'Domain'.strtoupper($m[1]);
}
By the way, to let you know, your way of writing a code, with no indents or spaces, is terrible.

You have an error in your == statement.
Should be like this :
$q1 = $_GET['question'];
if ($q1 == "domaina.com"|| $q1 == ".domaina.com"|| $q1 == "domaina.co")
{
$q2 = 'domaina';
$q3 = 'DomainA';
}
elseif ($q1 == "domainb.com"|| $q1 == ".domainb.com"||$q1 == "domainb.co")
{
$q2 = 'domainb';
$q3 = 'DomainB';
}
elseif ($q1 == "domainc.com"||$q1 == ".domainc.com"||$q1 == "domainc.co")
{$q2 = 'domainc';
$q3 = 'DomainC';
}
else {$q2 = 'noquestions';
$q3 = 'NoQuestions';
}
You could also use in_array :
$q1 = $_GET['question'];
if(in_array("$q1", array("domaina.com",".domaina.com",""domaina.co"")))
{
$q2 = 'domaina';
$q3 = 'DomainA';
}
//...

The following will always evaluate to true.
if ($q1 == "domaina.com"||".domaina.com"||"domaina.co")
You probably meant:
if ($q1 == "domaina.com"||$q1 == ".domaina.com"||$q1 == "domaina.co")

Your conditionals in the ifs are wrong. Try fixing those first.
if ($q1 == "domaina.com"||$q1 == ".domaina.com"||$q1 == "domaina.co")
{
...
}

you need to format it like so:
if ($q1 == "domaina.com" || $q1 == ".domaina.com" || $q1 == "domaina.co")
What you were doing was interpreted as:
if ($q1 == ("domaina.com" || ".domaina.com" || "domaina.co"))
// interpreted as:
if ($q1 == (((bool)"domaina.com" || (bool)".domaina.com" || (bool)"domaina.co"))
// interpreted as:
if ($q1 == ((true || true || true))
// interpreted as:
if ($q1 == true)
// interpreted as:
if ((bool)$q1 == true))
Note also that had you use the === operator instead, your last condition would have been the one that always evaluated to true instead of the first one, since you would be comparing a string with the result of a boolean operation.

You could simplify your if statements by using the strpos function like this:
$q1 = $_GET['question'];
if (strpos($q1, "domaina") === true) {
$q2 = "domaina";
$q3 = "DomainA";
} elseif (strpos($q1, "domainb") === true) {
$q2 = "domainb";
$q3 = "DomainB";
} elseif (strpos($q1, "domainc") === true) {
$q2 = "domainc";
$q3 = "DomainC";
} else {
$q2 = "noquestions";
$q3 = "NoQuestion";
}

I think you can simplify your code a bit:
<?php
$q1 = $_GET['question'];
$q2 = getDomain($q1);
$q3 = ucfirst(substr($q2, 0, -1)) + strtoupper(substr($q2, -1));
function getDomain($url){
$arrA = array('domaina.com', '.domaina.com', 'domaina.co');
$arrB = array('domaina.com', '.domaina.com', 'domaina.co');
$arrC = array('domaina.com', '.domaina.com', 'domaina.co');
$q1 = strtolower($url);
if(in_array($q1, $arrA))
return "domaina";
if(in_array($q1, $arrB))
return "domainb";
if(in_array($q1, $arrC))
return "domainc";
return '';
}
?>

Related

Multiple lines if statements

I am checking around 20 variables like the following and I was wondering if there is a faster way (less lines) to do the same:
if ($data1 == 1) {
$res1 = "Yes";
} else {
$res1 = "No";
}
if ($data2 == 1) {
$res2 = "Yes";
} else {
$res2 = "No";
}
if ($data3 == 1) {
$res3 = "Yes";
} else {
$res3 = "No";
}
etc..
There are a few ways:
1) foreach loop:
$array = [$data1, $data2, $data3];
foreach ($array as $key => $value)
{
${'res'. $key} = ($value == 1 ? 'yes' : 'no');
}
Although as Qirel pointed out, this probably isn't the best thing to do. If you need to name new values $name. $x then it's probably better as an array:
$array = [$data1, $data2, $data3];
$res = [];
foreach ($array as $key => $value)
{
$res[$key] = ($value == 1 ? 'yes' : 'no');
}
2) function:
function checkVal($value)
{
return ($value == 1 ? 'yes' : 'no');
}
$res1 = checkVal($data1);
3) ternary - not necessarily not repeating code, but it's shorter:
$res1 = ($data1 == 1 ? 'yes' : 'no')
$res2 = ($data2 == 1 ? 'yes' : 'no')
$res3 = ($data3 == 1 ? 'yes' : 'no')
This should also work -
// number of variables to check
$num = 3;
// Loop for checking all the variables as per naming convnetions followed
for ($i = 1; $i <= $num; $i++) {
// set yes/no depending on the data set
${'res' . $i} = ${'data' . $i} == 1 ? 'yes' : 'no';
}
I don't know the context but from what I can see my advice is to create an array of $data1, $data2, $dataN and loop all these values to create another array with all checks
$values = [$data1, $data2, $data3, $data4];
$responses = array_reduce($values, function ($a, $b) {
$a[] = 1 === $b;
return $a;
}, []);

PHP: Assign multiple variables in if statement

I don't seem to be able to assign multiple variables in an "if" statement. The following code:
<?php
function a ($var)
{
if ($var == 1)
{
return 'foo';
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 'bar';
}
return false;
}
if ($result1 = a(1) && $result2 = b(1))
{
echo $result1 . ' ' . $result2;
}
?>
Returns "1 bar" rather than "foo bar". If I remove the second condition/assignment it returns "foo".
Is there a way to assign multiple variables in an "if" statement or are we limited to just one?
This is all about operator precedence
<?php
function a ($var)
{
if ($var == 1)
{
return 'foo';
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 'bar';
}
return false;
}
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
?>
https://repl.it/IQcU
UPDATE
assignment operator = is right-asscoiative, that means, evaluation of operand on rhs has precedence over the lhs operand.
thus,
$result1 = a(1) && $result2 = b(1)
is equivalent of,
$result1 = (a(1) && $result2 = b(1))
which evaluates
$result1 = ("foo" && [other valild assignment] )
which will result that,
$result1 becomes true
and echo true/string value of boolean true (strval(true)) outputs/is 1
you can also check that revision, https://repl.it/IQcU/1
to see that below statement
$result1 = a(1) && $result2 = b(1)
is equivalent of this one.
$result1 = (a(1) && $result2 = b(1))
Need to add parentheses() in each assignment like below:-
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
Output:- https://eval.in/804770
Correct explanation is given by #marmeladze here:-
Why 1 bar is coming through OP's code
The last if statements need some brackets, it should have been:
if (($result1 = a(1)) && ($result2 = b(1)))
{
echo $result1 . ' ' . $result2;
}
This ensures that things in the bracket are executed first and it will help.
You have to add == to check a condition.
Try this,
if ($result1 == a(1) && $result2 == b(1))
{
echo $result1 . ' ' . $result2;
}
Checked with belo example
<?php
function a ($var)
{
if ($var == 1)
{
return 1;
}
return false;
}
function b ($var)
{
if ($var == 1)
{
return 2;
}
return false;
}
if (1 == a(1) && 2 == b(1))
{
echo 'success';
}
?>

How do you concatenate two strings in a for loop in PHP?

I didn't explain very well the first time. I'll try again.
I want to simplify these if statements with a for loop. CatagoryX is (1-3) so I thought I could cycle through the variable, but I don't know how to write the code.
I want to simplify this with a for loop.
$sqlCommand = "SELECT id, catagory1, catagory2, catagory3 FROM listofbooks;
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error());
while($row = mysqli_fetch_array($query)){
//check to see if catagory1 is an 18, 19, or 20, and make $bookcatagory=the name
if (catagory1 == "18"){
$bookcatagory == "Thriller";
catagory1 = "";
}
if (catagory1 == "19"){
$bookcatagory == "Fantasy";
catagory1 = "";
}
if (catagory1 == "20"){
$bookcatagory == "Science Fiction";
catagory1 = "";
}
//check to see if catagory2 is an 18, 19, or 20, and make $bookcatagory=the name
if (catagory2 == "18"){
$bookcatagory2 == "Thriller";
catagory2 = "";
}
if (catagory2 == "19"){
$bookcatagory2 == "Fantasy";
catagory2 = "";
}
if (catagory2 == "20"){
$bookcatagory2 == "Science Fiction";
catagory2 = "";
}
//check to see if catagory2 is an 18, 19, or 20, and make $bookcatagory=the name
if (catagory3 == "18"){
$bookcatagory2 == "Thriller";
catagory3 = "";
}
if (catagory3 == "19"){
$bookcatagory2 == "Fantasy";
catagory3 = "";
}
if (catagory3 == "20"){
$bookcatagory2 == "Science Fiction";
catagory3 = "";
}
}
You don't need a loop.
Try this!
$bookCategories = Array("18"=>"Thriller", "19"=>"Fantasy", "20"=>"Science Fiction");
while($row = mysqli_fetch_array($query)){
$bookcategory[] = $bookCategories[$category];
}

Confusion with `if` `else` and `while`

I have a code where it should check if the result equals to 8 it need to show something and if not it need to show something else and all of that happens inside of a while loop.
while ($row_fpages2 = mysql_fetch_array($result_fanpage2))
{
if ( $row_fpages2['client'] != NULL ) {
//GRAPHS
$sql = "SELECT likes, date FROM statistics_pages WHERE idnum = '".$idnum."' AND page_name = '".$row_fpages2['page_name']."' ORDER BY `statistics_pages`.`date` DESC LIMIT 8";
$result2 = mysql_query($sql) or die(mysql_error());
if ($result2) {
$data = array();
while ($row = mysql_fetch_assoc($result2)) {
$data[] = $row["likes"];
}
if ($result2 == 8) {
$c_data = count($data)-1;
$final = array();
for ($i = 0; $i < $c_data; $i++) {
$final[] = getZeroResult($data[$i], $data[$i+1]);
}
$data_string = join(",", $final);
$stats = '<img src="http://chart.apis.google.com/chart?chs=240x140&cht=ls&chd=t:0,0|'.$data_string.'&chg=20,20&chls=0.75,-1,-1|6,4,1&chm=o,FF9900,1,-1,7,-1|b,3399CC44,0,1,0"></img>';
} else {
$stats = '<img src="images/stats_un.jpg"></img>';
};
} else {
print('MySQL query failed with error: ' . mysql_error());
}
echo '...';
The problem is that the first output always showing the ( == 8) (even if it is not equals to 8) instead of the else output.
Then if i have 2 or more everything comes above the first one is correct but the first one is still showing the ( == 8).
Any help?
You do the following which is incorrect:
$result2 = mysql_query($sql) or die(mysql_error());
...
if ($result2 == 8) {
The return value of mysql_query is a resource not an int. What is that you are trying to do there ?
May be you would like to use
if(strlen($result2) == 8){
...
}
instead of
if($result2 == 8){
...
}
Hope that solves your problem.

php | Simple question on conditional statement

I'm new to php and I would like to have a conditional statement like this:
if ($foo != 'Any') { $condition .= '$this_foo == $foo &&';}
if ($bar != 'Any') { $condition .= '$this_bar == $bar &&';}
if ($txt != 'Any') { $condition .= '$this_txt == $txt &&';}
$condition .= '$num1 > 0 && $num2 < 1000';
if (...[php would parse the $condition variable])
{
someoperations
}
What is the proper syntax for the if statement to parse the variable $condition? So the conditional statement depends on the other variables and to prevent a long nested conditional statement.
Thanks in advance!
Well it's not exactly parsing, but you could evaluate your condition as the code is executed.
$condition = true;
if ($foo != 'Any') { $condition = $condition && ($this_foo == $foo);}
if ($bar != 'Any') { $condition = $condition && ($this_bar == $bar);}
if ($txt != 'Any') { $condition = $condition && ($this_txt == $txt);}
$condition = $condition && ($num1 > 0 && $num2 < 1000);
if ($condition)
{
someoperations
}
So let's say that $foo != 'Any' is true, that would result in
$condition = true && ($this_foo == $foo) && ($num1 > 0 && $num2 < 1000);
Let's pretend $this_foo == $foo, $num1 == 45 and $num2 == 2300
$condition = true && true && (true && false);
$condition = false;
and your if won't execute.
I believe what you want is
if (eval("return " . $condition)) {...}
Making sure to check for the FALSE case if the parsing fails.

Categories