I have some code that isn't working yet, before I debug I want to make sure that this syntax or method can indeed work and actually only execute the mysql_query if the last condition is true.
Also, is this a relatively safe practice?
I couldn't find anything relating to this, I figured someone putting it in English would help clear this up for me.
if($var1 == $var2) {$new = 1;}
if($vara == $varb) {$old = 1;}
if($new = 1 && $old = 1) { mysqli_query($somequery);}
This won't work because of the single =.
Go for:
if($var1 == $var2) {$new = 1;}
if($vara == $varb) {$old = 1;}
if($new == 1 && $old == 1) { mysqli_query($somequery);}
Or, ideally:
if ($var1 == $var2 && $vara == $varb) {
mysqli_query($somequery);
}
Top hint to stop things like if ($var = 1) typos - switch the comparisons around and put the constant first.
If you write if ($var = 1) then $var becomes 1 and is always true, but if you write if (1 = $var) you get an error, which is exactly what you want (and the same happens if your use a string if ("yes" = $var).
It been hammered into us to put the variable first since forever, but you're far better off doing it the other way around.
Related
$a = $_POST['year'];
$b = $_POST['mileage'];
$c = is_numeric($a);
$d = is_numeric($b);
if ($c == False && $d == False) {
echo = "$c & $d variables are not numeric";
} else {
echo = "$c & $d variables are numeric";
}
This is a code that I whipped while learning PHP. Is there anyone that can help me simplify them. I don't like how it looked. I feel that it is too long. Beginner here (",)
Sometimes breaking down the way you set values can be useful, especially with complex calculations as it helps to debug the code.
But with simple assignments it is better (IMHO) to try and reduce the number of extra steps you make in your code. Setting a variable to then use it in another step is an overhead for both the computer (although negligible) but also adds extra lines of code. So assuming you just want to show if they are both numeric or not you can roll up all of those variables into the if statement...
if (is_numeric($_POST['year']) == False && is_numeric($_POST['mileage']) == False) {
echo "variables are not numeric";
} else {
echo "variables are numeric";
}
This does assume you have already checked that $_POST['year'] and $_POST['mileage'] are set (as does your code), you can use $_POST['mileage'] ?? '' if you want to make it more flexible.
Also the code only says the variables are not numeric if both values are not numeric. Change the && to || for either values not being numeric.
So I have an if-statement and I am not sure how is the best way to write it. Or if there is a proper way of writing it. Can I just use && every time or should I separate them with more () or does it really matter, is there a difference in performance ect?
$a = 10;
$b = 20;
$c = 8;
$d = 25;
$e = "";
$f = "not blank";
// FIRST EXAMPLE
if (!empty($e) && !empty($f) && $a <= $c && $b <= $d)
{
// do something here
}
OR
if ( (!empty($e) && !empty($f)) && ($a <= $c && $b <= $d))
{
// do something here
}
It only depends of your needs. Don't use brackets when you don't need it. It making code harder to read. In your case you shouldn't use brackets, just:
if ( !empty($e) && !empty($f) && $a <= $c && $b <= $d)
{
// do something here
}
In this case there is completely no need to use more brackets because you have only &&. As it comes to performance, less brackets - less work for interpreter.
Generally whether you need to use brackets depends on the precedence of the operators you are using in the condition of the if statement. See the official PHP documentation on it for more detail.
Personally, in the case of if statements (and code in general within reason) I favour readability above all.
For instance, with the following if statement you suggested:
if (!empty($e) && !empty($f) && $a <= $c && $b <= $d)
{
// do something here
}
For someone who is not familiar with the code, it can initially take a bit longer to see what's happening. There are many ways to combat this. One example is splitting the condition into separate if statements and maybe throwing exceptions if it fits in with your logic. In this case your example could become something like this:
if (empty($e) || empty($f))
{
// throw exception as one or both of $e or $f is empty
}
if ($a <= $c && $b <= $d)
{
// do something here
}
The example may not be logically correct but hopefully it helps in throwing a different perspective on things.
You need to keep each statement in different brackets
if ( (!empty($e) && (!empty($f) && ($a <= $c) && ($b <= $d))
{
// do something here
}
I am trying to get this:
if($a[2] > $b[2] && $c[2] < 3) echo "bingo";
But because the condition is retrieved from database, I need to get the whole condition into a variable and then somehow find a way to change the variable back into a condition. I thought it will be something along this line:
$condition = "$a[2] > $b[2] && $c[2] < 3";
$evaledCondition = eval("$condition;");
if($evaledCondition) echo "bingo";
Apparently it didn't work. Am I missing something?
eval() returns NULL unless return is
called in the evaluated code
$evaledCondition = eval("return $condition;");
The following two ifs produced different results(first if echos hi, second does not), why? why didn't the variable assignment on $t work? is this due to $t's local scope inside the if conditional?
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"]) && !empty($t)){
echo 'hi'
}
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
if(!empty($t))echo 'hi'
}
&& has a higher precedence than =, hence the first expression is evaluated as:
isset($_REQUEST['test']) && $t = (trim($_REQUEST['test']) && !empty($t))
Since !empty($t) is evaluated before anything is assigned to $t, the expression is false. You could fix this by explicitly setting parentheses, or by using a less awkward way to write it:
if (isset($_REQUEST['test']) && trim($_REQUEST['test'])) {
echo 'hi';
}
trim($_REQUEST['test']) will evaluate to true or false just by itself, no empty necessary. If you actually need the trimmed value later, you can save it like so:
if (isset($_REQUEST['test']) && ($t = trim($_REQUEST['test']))) {
echo 'hi';
}
If you make minor modification like this in your code:
if(isset($_REQUEST["test"]) && ($t=trim($_REQUEST["test"])) && !empty($t)){
echo '1: hi<br/>';
}
if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
if(!empty($t))
echo '2: hi<br/>';
}
Then both 1: hi and 2: hi will be printed. Difference is parenthesis around first $t assignment.
Simple but this has always bothered me. Which is the best way to condition statement?
$foo = '1';
if($foo === '1' || $foo === '2' || $foo === '3')
{
// foo matches
}
or
if($foo === '1' || '2' || '3')
{
// foo matches
}
Which step works and is better. is there a better solution?
The second version will always evaluate to true.
If you want to compact the comparison against multiple alternatives then use:
if (in_array($foo, array('1', '2', '3') )) {
If you want to closely match the exact comparison === then you would however need:
if (is_string($foo) && in_array($foo, array(...))) {
$foo = 1;
if(in_array($foo, array(1, 2, 3))){
//foo matches
}
This is an alternative:
if($foo>0 && $foo<4){
}
Second if statement won't work. PHP doesn't work like that. Any number other than 0 (including negatives) evaluates to true when alone in an if statement. This is why you can do something like if(count($array)) without specifying that count($array) must be greater than 0.
Would be the same as if you had said:
if($foo === 1)
{}
elseif(2) //This will always trigger if $foo !== 1.
{}
elseif(3) //This will never trigger because of the last one
{}
Each condition is it's own self contained condition. Instead of reading it as just "or" or "and" read it as "or if" and "and if". So if $foo is 1 or if 2 or if 3 instead of if $foo is 1 or 2 or 3
If it's just numeric, then amosrivera's solution is the best. If it's for other types of data, then webarto/mario have a good solution.