How to write multiple variable if statement in php - php

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
}

Related

Php check if 5 variables are the same value

In php I need to check if 5 variables are the same value, and then proceed.
Instead of doing
if($a == 'logged' && $b == 'logged' && $c == 'logged' && $d == 'logged' && $e == 'logged')
{
// Code to run here
}
Is there a different way to do it? Like:
if($a,$b,$c,$d == 'logged')
Something like that possible..?
You can use something like this
$values = array($a, $b, $c, $d, 'logged');
if(count(array_unique($values)) === 1) {
//All elements are the same
}
I recommend against trying to shorten that. There is no more compact notation available to my knowledge apart from optical effects, none that the php parser accepts. The efficiency would not be better, since internally the same comparisons have to be done anyway.
Instead I usually try to enhance the readability of the code instead and use reversed notation, since human time is much more expensive than computer power these days :-)
if ( 'logged' == $a
&& 'logged' == $b
&& 'logged' == $c
&& 'logged' == $d
&& 'logged' == $e ) {
// Code
}

PHP - is this syntax possible and is it safe

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.

Multiple Conditions in a while loop PHP

What is the correct way to use boolean operators to have multiple conditions in a while loop?
I have this script here that I feel SHOULD work, however it comes up blank when I run it.
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
for ($i=0; $i<strlen($string); $i++) {
if ($string[$i] == chr(34)) {
// chr 34 is ascii value for double quote chr 44 is for comma
while (($string[$i] != chr(34)) && ($string[$i+1] != chr(44))) {
echo $string[$i];
$i++;
}
}
}
Ideally what i want is for the script to echo the the given string up until the pointer ($i) reaches a double quote and one ahead of it is a comma. I feel like this is very simple and I am clearly missing something obvious.
if ($string[$i] == chr(34)) {
while (($string[$i] != chr(34)) && ($string[$i+1] != chr(44)))
Your if statement will run if this character is a quote. The while statement will run for as long as this character isn't a quote (and isn't a comma)
The two are exclusive. I think you might be able to get around it by incrementing $i after the if statement, but there's almost certainly an easier way of doing this.
The if and the while says the opposite condition... which means the while will never have a true. I guess you wanted to check the next character ?
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
for ($i=0; $i<strlen($string); $i++)
{
if ($string[$i] == chr(34))
{
while (($string[$i+1] != chr(34)) && ($string[$i+1] != chr(44))) // notice the $i+1
// chr 34 is ascii value for double quote chr 44 is for comma
{
echo $string[$i];
$i++;
}
}
}
The inner loop will not end at the end of the string.
Manipulation the loop control variable ($i) inside the loop leads to difficult code.
It makes it much harder to reason about it, and check if it is correct or not.
You should avoid it.
You get a better structure if you have only one loop that move through the string one char after another. Than use a variable to remember a state, for example $inside_quotes .
You have a logical flaw inside your loop which will cause it to iterate over the whole string but without doing any output.
Let's say:
$a = 1;
$b = 1;
while ($a == 1)
{
while ($a != 1 && $b == 1)
{
# will never come here.
}
$a++;
}
Because $a can never be 1 and !1 at the same time the condition you have put inside each other are blocking themselves.
One common way to solve this is to tokenize the string (scan the string) and then work on the tokens:
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
$token = strtok($string, '"');
while ($token !== false)
{
$token[0] !== ',' && (print "$token\n");
$token = strtok('"');
}
This produces (Demo) the following output:
JOHN
<31255555656>
DAHDI/1-1
Which might or might not be what you are looking for. A more detailed variant of this is to have a tokenizer/scanner that has state, one that can do more (but still has the shortcoming that the escapes of the quotation marks by doubling ("") them). As this is pretty bogus, I only link it. It is bogus because:
The actual function you're looking for is called str_getcsv:
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
echo implode("\n", str_getcsv($string));
Output (Demo):
"JOHN" <31255555656>
DAHDI/1-1
3948723
If you have a whole file, take a look at the SplFileObject.
Since you already located the first quote with the for statement you don't need to locate the same quote again with the for statement.
remove this: (($string[$i] != chr(34)) && along with the extra ) and the code will produce the following:
"""JOHN"" <31255555656>"DAHDI/1-1"
<?php
$string = '"""JOHN"" <31255555656>","DAHDI/1-1",3948723,,"",';
for ($i=0; $i<strlen($string); $i++) {
if ($string[$i] == chr(34)) {
while ($string[$i+1] != chr(44)) {
echo $string[$i];
$i++;
}
}
}
?>

In php how do you say if ($x == 1 or 2 or 3 or 4) {do function} without repeating code many times?

Im not great in php and I could do with a little help. I want to say something like
if ($x == 1 or 2 or 3 or 4) {do function}
but the only way i know how to do that is to go
if (($x == '1') or ($x == '2')) or...
which seems a long way of doing it. Is there a better way I am missing, like
if ($x == 1,2,3,4) {do}
Thanks for your answers!
you can use in_array function
$array = array(1,2,3,4)
if(in_array($x, $array)) {
// do something
}
switch ($x) {
case 1:
case 2:
case 3:
case 4:
// do
break;
}
Or you can use the in_array() function creating an array such as $a = array(1,2,3,4); and then do if (in_array($x, $a)).
If you are concerned about space, you can also use the shortcut:
if (in_array($x, array(1,2,3,4))) { /* do */ }
You can create an array of expected values and then use function in_array().
http://php.net/manual/en/function.in-array.php
If it's a range, you could do:
if ($x >= 1 && $x <= 4) { }
You could also construct an array and check if the number is in that array.
<?php
$data = array(1,2,3,4);
if(in_array($x, $data)){
// execute function
}
?>
All the above ideas are good. I am going to show another way, that is not better, but is different.
You can store comparations in variables, to use later or combine. This helps readability, and make complex expresions easy to create and read. It obviusly remove any repetition.
$is_number = ($str=="one" or $str=="two" or $str=="tree");
$is_english = ($str=="one" or $str=="horse");
$is_french = ($str=="baguette" or $str=="amie");
$is_fun = $is_french or $is_english;
if($is_french and !$is_number){ ... }

php if statement with one of two conditions if( a < b) or (b=0)

I have some huge blocks of code and I would like to avoid using elseif so the question is : Is it possible to construct an IF function with two possibilities in the same statement ?
something like if( a < b) or (b=0)
{
statement
}
if( ($a < $b) || ($b==0) )
{
//do something
}
or even better
if( ($a < $b) || (0==$b) )
{
//do something
}
so you don't accidentally assign 0 to $b.
if( ($a<$b) OR ($b == 0) )
{
//do something
}
Parenthesis in this case are not necessary, just added for clarity.
($a < $b ? 'a is smaller' : 'a equals or is greater');
Quick and easy, but not easily to maintain (personal opinion).

Categories