I have something simple I'm trying to accomplish with less repetition.
By default, I want a div to be shown, however if $x == 1, then check to see if $y != 1, and if $y doesn't, then don't show the block.
However the best I can come up with is the following:
if($x) {
if($y != 1) {
echo '<div>display block</div>';
}
} else {
echo '<div>display block</div>';
}
This seems a bit repetitive.
I know I can tweak it a bit and do something like:
$displayBlock = '<div>display block</div>';
if($x) {
if($y != 1) {
echo $displayBlock;
}
} else {
echo $displayBlock;
}
But even still, I have a feeling that there is a way to do this whole if if else thing which I can't see right now.
How do you accomplish the above with less if statements? So: if $x != 1 (default), then show the displayBlock. if $x == 1, and $y != 1, then show the display block. If $x == 1 && $y == 1, then do not show the displayBlock.
if (!$x || $y != 1) echo $displayBlock;
+1 to zerkms's answer - it's on the money. To help you solve problems like this in the future, it might be handy to look at truth tables Karnaugh maps.
You essentially have two checks:
a) $x (coerced to true or false)
b) $y != 1
$y != 1
T F
$x T 1 0
F 1 1
So, from that you can see that if $x is falsey, or $y != 1 is true, then you should show the display block, hence:
if (!$x || $y != 1) echo $displayBlock;
In order to keep the amount of code down, you could use a more mathematical approach rather than logic; e.g.
<?php
if($x+$y != 2){echo $displayBlock;}
?>
The display box only stays off when the sum of x and y equals 2.
Check these out. http://www.php.net/manual/en/language.operators.logical.php
$displayBlock = '<div>display block</div>';
if((($x) && ($y != 1)) || (!$x)) {
echo $displayBlock;
}
How did we come to this solution?
Look at your statement, and dissect it logically:
If x is true ... and ... y is 1... then print.
Which brings us to:
(($x) && ($y != 1))
See? X is truth AND y is one. That brigns you down to
if (($x) && ($y != 1)) {
//Do that thing
} else {
if (! $x) {
//Do that thing
}
}
Which we can write simply as...
if (($x) && ($y != 1)) {
//Do that thing
} else { if (! $x) {
//Do that thing
}
Okay, so what's this say?
If conditionA do something, or if condition B do something.
Oh, there's an OR.
So, condtion A || condition B
Which of course, brings us back to...
if((($x) && ($y != 1)) || (!$x)) {
I put in more braces than required in there so you can see the flow of things.
Related
I have a question about IF statements with multiple logical OR operators.
If we let:
$x=1;
A. I typical would write a IF statement comparing two items like this:
if($x == 1 || $x == 2) echo 'good';
else echo 'bad';
B. But, is this a valid IF statement? If not, why? (because it seems to work)
if($x == (1 || 2)) echo 'good';
else echo 'bad';
C. I typical would write a third comparison like this:
if($x == 1 || $x == 2 || $x == 3) echo 'good';
else echo 'bad';
D. What about this, following suit with B, above? (it does not seem to work)
if($x == (1 || 2 || 3)) echo 'good';
else echo 'bad';
The example in B, above works, but not the example in D. Why?
I cannot find any PHP documentation as to why.
Here is what happens for every version:
A. $x == 1 || $x == 2
PHP will compare $x with the value 1, this is true so it can short-circuit the if and echo 'good'.
B. $x == (1 || 2)
PHP will evaluate 1 || 2 because parentheses indicate the priority, as the result should be a boolean expression it will cast 1 to a boolean which evaluates to true so the expression becomes $x == true.
Now PHP will evaluate this expression. First it will cast both types to the same, according to the documentation, it will "Convert both sides to bool". So, same as above, as $x is 1 it will be cast to true and then the expression becomes true == true which is true.
C. $x == 1 || $x == 2 || $x == 3
It is the same as A.
D. $x == (1 || 2 || 3)
It is quite the same as B.
And, for the record 1 == (1 || 2 || 3) evaluates to true.
I am currently teaching myself web development/ programming and to learn php i have built a simple program. The program takes user input and based on a series of math algorithms and calculates 7 random lottery numbers. The code is working fine but i want to improve it. The code is very repetitive and i want to simplify it by creating my own functions. I have created the first function that takes the users input, simply does some maths and then returns some values.
For Example...
<?php
function some_maths($int1 $int2 $int3){
$x = $int1 + $int2;
$y = $int2 * $int3;
$z = $y * $x;
return $x
....}
So this is pretty straight forward, but what i want to do now is take the values of X, Y, Z and create a function that checks to make sure they're not matching, or that they're not less than 1 or greater than 59. I used a while loop in my original code that goes like this:
while($x == $y || $x == $z || $x <1 || $x >59){
if( x> 59 || x < 1){
if (x<1){
do{ $x+=$int}while($x <1);
}elseif ($x > 59){
do{ $x-=$int}while($x >59);
}else $x++;
}
This seems to work fine but i don't want to have to repeat the same code over and over. I am sure there has to be a better way? Could i put the values into an array and maybe do it that way? What would be the best solution for this?
Your question is kind of vague but if I had to write a function to check if three numbers weren't equal and were < 59 and >1 this is how I would do it
function validateNumbers($x , $y , $z)
{
if(equal($x,$y)) return false;
if(equal($x,$z)) return false;
if(equal($y,$z)) return false;
if($x>59||$x<1) return false;
if($y>59||$y<1) return false;
if($z>59||$z<1) return false;
return true;
}
function equal($x , $y)
{
if($x == $y)return true;
else return fasle;
}
So far I only see two (pretty straightforward) things:
Your function prototype in the first example is missing commas between the parameters. Instead of function some_maths($int1 $int2 $int3) it should read function some_maths($int1, $int2, $int3).
In your second example a closing } is missing. But if I am interpreting your stuff correctly, the outer if-clause is redundant. Thus, the snippet can be simplified to:
Second example:
while($x == $y || $x == $z || $x <1 || $x >59){
if (x<1){
do{ $x+=$int}while($x <1);
}
elseif ($x > 59){
do{ $x-=$int}while($x >59);
}
else $x++;
}
There may be more room for improvement (e.g. slim down the condition of the outer while loop) - but for that we would need more context (what happens before your loop, what is $int, ...).
unable to get my else if statement to work, does anyone have any ideas? it works without the else if....
$waveFeet = round("$ar2");
if ($waveFeet >= 2) {
echo $waveFeet - 1;
}
else if ($waveFeet > 5) {
echo $waveFeet - 2;
}
else
{
echo "$wavefeet";
}
also as a side question, can anyone tell me how to change my round() to make it always round (down) instead of rounding up or down...?
Using the third argument of round you can round it down
echo $waveFeet = round($ar2, 2, PHP_ROUND_HALF_DOWN);
and for your if your else if condition will never got true as if the $waveFeet is greater than or equal to 2, the first condition will be true hence your elseif condition will never be true.
You should be changing it to
if ($waveFeet > 5) {
echo $waveFeet - 1;
}
else if ($waveFeet >= 2) {
echo $waveFeet - 2;
}
else
{
echo $wavefeet;
}
Try the statement with a particular value, say $waveFeet = 10;, then step through the code. The first condition succeeds, so the later branches are never checked. In fact, the only time the first branch isn't entered is when $waveFeet < 2, in which case the last branch body will be executed. Thus the middle branch is never executed. The more exclusive case should come first:
if (5 < $waveFeet) {
...
} elseif (2 <= $waveFeet) {
...
} else {
# $waveFeet < 2
...
}
To be completely safe, you can specify both boundary conditions:
...
} elseif (2 <= $waveFeet && $waveFeet <= 5) {
...
The inefficiency due to redundancy is minimal and the code is clearer. As you get more experienced, you can leave off this sort of thing.
If you wish to round even negative numbers down, use floor. If you wish to round towards zero (i.e. truncate), cast to an int:
$waveFeet = (int) $ar2;
you can use floor for down round
$waveFeet = floor($ar2);
if ($waveFeet > 5)
echo $waveFeet - 2;
else if ($waveFeet >= 2)
echo $waveFeet - 1;
else
echo $wavefeet;
you have to first check for 5 bcz 5 is big no than 2 and your first condition >= 2 also satisfied if no >5 so control go to first condition rather than second....
Theres nothing wrong in your code ( except that you can pass argument to function without quotes ). The way you are checking it is wrong.
it wont go to else if condition because the condition will be satisfied in the first check itself .
PHP buil-in floor() and ceil() functions round a number down and up respectively. I recommend posting the error you get so we can help you faster =)
Try this:
$waveFeet = floor($ar2);
if ($waveFeet >= 2 && $waveFeet <= 5 ) {
echo $waveFeet - 1;
} else if ($waveFeet > 5) {
echo $waveFeet - 2;
} else {
echo $wavefeet;
}
Note the change in the first condition (added && $waveFeet <= 5)
I think the problem might be that the ranges you use in your first and second conditions are overlapped, and it is very likely that in the case, let's say, $waveFeet == 6 PHP evaluates your first condition (originally $waveFeet >= 2), and it happened to be true, so PHP does not test the else if statement... Whenever it's possible to use disjunct conditions, I recommend you to do it...
URL
x.php?foo=100
x.php
$x = $_GET['foo'];
if ($x = 100) {
echo "yeah";
}else{
echo "no";
}
My code doesnt work, where is error?
You are using a single equal mark (=) instead of two in the IF statement (if ($x = 100) {).
A single equal mark will set the value 100 into $x, and then evaluate the IF statement with it - which evaluates to true in PHP.
if ($x == "100")
or
if (intval($x) === 100)
if ($x = 100) {
sets $x to 100 and evaluates the result. You want:
if ($x == '100') {
It is because you are using an assignment statement instead of checking for equality in the line:
if ($x = 100)
Try
if ($x == 100)
instead.
you are not comparing value of x, you are saying that x is equal to 100
try
if($x == 100) { echo "yeah"; }
first check with isset($_REQUEST['foo']) or isset($_GET['foo'])
This is what i have currently
if ($j == 1 || $j == 2 || $j == 3)
Is there a simpler way of writing this. Something like...
pseudocode
if ($j == 1-3)
Here's one way using in_array()
if (in_array($j, array(1,2,3)))
{
//do something
}
Or how about using range() to make the array
if (in_array($j, range(1,3)))
{
//do something
}
However, building an array just to check a narrow, contiguous range like that is pretty inefficient. So how about simply:
if ($j >= 1 && $j <= 3)
{
//do something
}
If other values of $j will trigger different action, a switch might be more appropriate...
switch($j)
{
case 1:
case 2:
case 3:
//do something
break;
}
If it's a range, you can simply do:
if ($j >= 1 && $j <= 5) ...
Paul's good one, but if you have a large number then you may want to use range:
if (in_array($j, range(0, 100)))
{
}