if and else statement mixed up - php

I am doing the following if else statement below but number (//1) and number (//4) get executed at the same time, I am finding it abit hard to understand why.
<?php
//1
if($a == 1 && count($b) == 0) {
// do this
}
//2
elseif ($a == 1 && count($b) > 0) {
// do that
}
//3
if($a== 0 && count($b) == 0) {
// do a different thing
}
//4
else {
// do the last thing
}
?>
I have done this and it works but i think the should be a more suitable way for not using elseif for this.
else if($a== 0 && count($b) > 0) {
// do the last thing
}

but number (//1) and number (//4) get executed at the same time
It's because you don't have else before the if on //3
//3
if($a== 0 &&
Change to elseif($a== 0 &&
At the moment you have two separate IF conditions

You're missing a closing brace after your first if.
Also, you have a weird operator inside your first condition : $$. Maybe you intended to type &&?

$a = 10;
if ($a == 5) {
echo 'ok';
} elseif ($a == 10) { // $a is equal to 10, so it executes;
echo 'not_ok';
}
if ($a > 20) {
echo 'ok_ok';
} else { // $a is not >20 so else statement executes
echo 'not_not';
}
final result: not_oknot_not
If you are performing such tests on one and the same assignee, but different values, you might not want to execute more than one?
I guess you need elseif where third block is if
if ($a == 5) {
echo 'ok';
} elseif ($a == 10) { // $a is equal to 10, so it executes and stops the block;
echo 'not_ok';
} elseif ($a > 20) {
echo 'ok_ok';
} else { // $a is not >20, but the block was stopped on first elseif
echo 'not_not';
}
produces not_ok
Even if you move the else statement after the first elseif block as was suggested
if ($a > 20) {
echo 'ok_ok';
}
will execute, and if it's true, it will produce result, which again will result in double result

You might want to do this...
if ($a == 1 && count($b) == 0) {
// do this
}
//2
elseif ($a == 1 && count($b) > 0) {
// do that
}
elseif ($a== 0 && count($b) == 0) {
// do a different thing
}
else {
// do the last thing
}
The reason they get executed at the same time is that... Well technically they're not executed at the same time since it's procedural, but they both get executed because they are both different if else conditions. If you want only 1 execution, you should combine them :)

Related

PHP If Statement is met display Either

I am familiar with using if else statement but my problem is how to display either if the condition is met.
if ($a == 1) {
echo 'B' OR 'C'; // just for reference
}
I have finally figure this out using nested loop
if ($a == 1) {
choiceresult = mt_rand(1,2)
if (choiceresult == 1) {
echo 'B';
}
if ( choiceresult == 2) {
echo 'C';
}
}
you have to fix your condition first :
if($a == 1)
Instead pf
if($a = 1)

Running same code in different conditions in PHP

I am trying to reduce/simplify the following code as it looks to have repeated elements:
<?php
if ($condition == true) {
if ($a > $b*0.5) {
echo "successful";
}
else {
echo "missed";
}
}
else {
if ($a > $b) {
echo "successful";
}
else {
echo "missed";
}
}
I don't want to use functions because if I did, I would have to define all the database things again.
<?php
if ( (condition1 && ($a > $b*0.5)) || (!condition1 && ($a > $b)) ) {
echo "successful";
else {
echo "missed";
}
?>
Your Code is missed Two (Semicoloumns)}.
Try By this
<?php
$a == 2;
$b == 4;
if ($a == 2 && $a > $b*0.5) {
echo "Suuccess";
}elseif($a != 2 && $a > $b){
echo "Suuccess";
}else{
echo "Fails";
}
In order to simplify your conditions, if the output is boolean (so only two outcomes possible) you could go with either one as default and only change it to the other depending on your decisions.
<?php
$outcome = false;
if($condition1 && ($a > ($b * 0.5))) {
$outcome = true;
}
else if($a > $b) {
$outcome = true;
}
if($outcome) {
echo "succesful";
}
else {
echo "missed";
}
This also combines the technique proposed by Sofyan Thayf to use boolean operators to merge conditions.
Another approach is to put the condition into a function and return early if succesful and have a missed fallthrough like
<?php
function decide($a, $b, $condition1) {
if($condition1 && ($a > ($b * 0.5)))
return true;
if($a > $b)
return true;
return false;
}
if(decide($a, $b, $condition1)) {
echo "succesful";
}
else {
echo "missed";
}
Both approaches enable you to extract the "same code" (being the echo) and IMHO add to readability and extensibility.
<?php
$factor = $condition ? 0.5 : 1;
if ($a > $b * $factor) {
echo "Hit";
}
else {
echo "Miss";
}
Could be further reduced using two ternary operators:
echo $a > $b * ($condition ? 0.5 : 1)
? 'Hit'
: 'Miss';
Ternary operators are useful shorthand for if/else conditionals.

use OR in if codition to print reverse results in php

I am trying echo result "OK" if ( 1 either both ) variable true, i did so far like this
<?php
$user_id = $_SESSION['user_id'];
$point= "select points from users where id = $user_id "; // in db right now points = 2000
$flag= "select m_boost from users where id = $user_id "; // in db right now flag = 1
?>
<div class="box border">
<div class="box-title">
<?php
if($point < 1000 || $flag = 0) {
echo "not ok";
} else { ?>
echo "ok";
<?php }?>
</div>
it's working if i do like this
if(($point == '2000') || ($flag == '0') ){
but i don't want == operator for $point i want less than < $point < '999'
The problem is :
Keep getting result " Not Ok " even one variable (flag = 1) is true in db
Expected Results:
i want to print "OK" if $point > 1000 or flag == 1,
try this
when you using OR condition you should careful about condition and login. you should implement logic in if condition instead of else.
if($point > 1000 || $flag ==1) {
echo "ok";
}else {
echo 'Not ok'
}
or AS YOU WANT
if($point < 1000 ) {
echo "Not ok";
}else if($flag ==0) {
echo 'Not ok'
}esle {
echo 'ok'
}
or you can use this way
$a=false;
if($point < 1000 ) {
$a=true;
}else if($flag ==0) {
$a=true;
}esle {
$a=false;
}
// you can use this variable in your condition.
if($a) {
echo "ok";
}else {
echo 'Not ok'
}
When you are using OR, if the first condition is met the second is disregarded.
Also, make sure you use double equals (==) for comparison, not single equals (=) which means assignment.
Therefore you want to replace this:
if($point < 1000 || $flag = 0) {
With one of these:
SWAPPED AROUND
if($flag == 0 || $point < 1000) {
or
USING && INSTEAD
if($point < 1000 && $flag == 0) {
Depending on what behaviour you're looking for. It's a little unclear - so any additional clarification from you would be helpful.
Once you get something that you think is working, try to test all possible combinations so that you can be confident it works how you wish.
$flag = 0
You're setting the variable's value to 0.
Example:
$flag = 1;
if($a < $b || $flag = 0){ //$flag's value is 0 now.
...
...
}
In conditions comparisons, the right operator is "==".
if($point < 1000 || $flag == 0) {
List of comparison operators
but i don't want == operator for $point i want less than < $point <
'999'
Didn't fully understood your goals, but maybe:
For checking a value in a range the right logical operator should be "and" (&&);
if($point > 0 && $point < 999){
List of logical operators
Update:
if $point > 1000 or flag == 1
if($point > 1000 || $flag == 1){
echo "ok"
}
if (!$flag && $point < 1000)
{
echo "Not OK";
} else {
echo "OK";
}
Writing this into a truth-table:
flag point result
0 < 1000 Not OK
1 < 1000 OK
0 >=1000 OK
1 >=1000 OK
Worked for me now as per my question
i think we are all here for some contribution reason, flagging down a question is not a way, if you got solution than respond otherwise my question was 100% clear.

If condition and empty variable

I have this code:
If(!isset($a) || empty($a))
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
The issue is that when $a is equal 0 then empty($a) is true and the first code runs. I need the second one to run. How do I do it?
if (isset($a) && $a == 0)
{
//code to run when $a is equal 0
}
elseif (empty($a))
{
// code to run when $a not set or empty;
}
else
{
//code to run in all other scenarios
}
Try this:
if((!isset($a) || empty($a)) && $a !== 0)
{
// code runs when $a not set or empty and $a is not 0;
}
elseif ($a === 0)
{
//code runs when $a is equal 0
}
else
{
//code runs in all other scenarios
}
Update:
Changed to typesafe comparison.
replace this and try
If(!isset($a) || $a=='')
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
I found the solution:
if (!isset($a) || (empty($a) && $a!==0))
{
//run code if $a is not set or is empty
}
elseif ($a===0)
{
//run code if $a is 0;
}
else
{
//all other scenarios
}
Empty function returns false when 0 (0 as an integer).
So your code should be
If(!isset($a))
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}

How to check for numbers only (including negative)?

how can I check for numbers only from -10 negative to +10 positive?
This is what I have, but I think it's not safe:
if(isset($_POST['number']) && ctype_digit($_POST['number']) && $_POST['number']>=-10 && $_POST['number']<=10){
//do something
}
and the form:
Input a number between -10 and 10: <input type="text" name="number" size="5" />
if( isset($_POST['number'])) {
$num = intval($_POST['number']);
if( $num >= -10 && $num <= 10) {
// do something
}
}
There are other ways, but that one will work. Anything that can't be converted to a number will be treated as zero. If this is not desired behaviour, add:
&& "".$num == $_POST['number']
To that inner IF statement, to ensure that no non-numeric characters were removed from the input.
Check whether a variable is a number including zero and negative values
$x = '-22';
if (isNumber($x, ['zero','negative']))
echo 'Yes';
else
echo 'No';
isNumber($x, $includes=[])
{
if (is_int($x)) {
if ($x === 0) {
if (in_array('zero', $includes))
return true;
} elseif ($x < 0) {
if (in_array('negative', $includes))
return true;
} else
return true;
} elseif (is_string($x)) {
if ($x == '0') {
if (in_array('zero', $includes))
return true;
} elseif ($x[0] == '-') {
if (in_array('negative', $includes))
return ctype_digit(substr($x, 1));
} else
return ctype_digit($x);
}
}

Categories