Running same code in different conditions in PHP - 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.

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)

Value outside of function is different from value inside function

In this elementary code, I check if a record exists with a particular itemId for a particular user and country.
The record returns 1 inside the function, but when it's outside, it's something totally different.
function recordExists(&$d) {
global $conn, $userId, $userCountryCode;
$sqlFindRecord = "select count(itemId) as recordCount from onr_items_mod where itemTempId = :itemTempId and itemStatus IN(0,5,8) and itemPublishedStatus = 2 and itemUserId = :userId and itemUserCountryCode = :userCountryCode";
$countRecord = $conn->prepare($sqlFindRecord);
$countRecord->execute(array(
":itemTempId" => $d,
":userId" => $userId,
":userCountryCode" => $userCountryCode
));
$countRecord->bindColumn('recordCount',$d);
echo 'This is D '.$d.' ---';
$row = $countRecord->fetch();
if($d == 0) {
return $d;
} elseif ($d == 1) {
return $d;
} else {
return false;
}
}
$d = 'US01'
if(recordExists($d) == 0) { //If the function returned 0
echo $d;
echo 'Was Zero';
} elseif (recordExists($d) == 1) { //If the function returned 1
echo $d;
echo 'Was One';
} else {
echo $d;
echo 'Neither Zero or One';
}
After I do the above, it's always 'Neither Zero or One'. Why is this? I tried the entire morning, but just cannot figure a way to sort this out.
This works, but not the above
function counter(&$a) {
if($a == 0) {
return $a;
} elseif ($a == 1) {
return $a;
} else {
return false;
}
}
$a = 1;
if(counter($a) == 0) {
echo $a;
} elseIf (counter($a) == 1) {
echo $a;
} else {
echo 'Umm...'.$a;
}
It will always be 'Neither Zero or One' why? Let's seee how it works
1. $d = 'US01'
2. if(recordExists($d) == 0) { //If the function returned 0
3. echo $d;
4. echo 'Was Zero';
5. } elseif (recordExists($d) == 1) { //If the function returned 1
6. echo $d;
7. echo 'Was One';
8. } else {
9. echo $d;
10. echo 'Neither Zero or One';
11. }
First $d is equal US01. It's ok. But after pass line #2 $d == 1 because you have set it in function (you have pass $d by reference).
So if statement in #2 line will return false beacuse thera are some records in database with itemTempId = 'US01'.
But now in the second if statement in line #5 variable $d = 1. So I suposse that you don't have any record with that itemTempId in your database. So the second statement (line #5) will also return false.
In my opinion you shouldn't pass it by reference.
EDIT
If you want to check if item exist in databse then yopu can ask only once. I really don't know what your goal is. But maybe this will be good
$d = 'US01';
$ret = recordExists($d);
if ($ret === 0) {
echo 'Was zero';
} elseif ($ret === 1) {
echo 'Was one';
} else {
echo 'Something else';
}
try to insert that into session variable and retrieve it in another method.
Hope it'll help.

if and else statement mixed up

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 :)

Adding conditions dynamically in php if condtion

I am trying to add a condition dynamically in the if condition . But it is not working . Please help me to fix the issue.
I am trying a code like this
$day_difference = "some integer value";
if(sheduled_time == 'evening'){
$condition = '>';
}else{
$condition = '==';
}
then
if($day_difference.$condition. 0){
echo "something";
}else{
echo "h";
}
An alternative to gerald's solution; I would suggest that you use a function that validates the inputs using a switch-case operation:
function evaluate ($var1, $operator, $var2)
{
switch $operator
{
case: '<': return ($var1 < $var2);
case: '>': return ($var1 > $var2);
case: '==': return ($var1 == $var2);
}
return null;
}
What you need is the eval() method.
I.e.
$var1 = 11;
$var2 = 110;
$cond1 = '$var1 > $var2';
$cond2 = '$var1 < $var2';
if(eval("return $cond1;")){
echo $cond1;
}
if(eval("return $cond2;")){
echo $cond2;
}
As justly noted beneath, you should exercise the necessary precautions when using this method!
This is not the way to do this.
Just define a function which returns true if the desired conditions are met.
For example, we can define the function decide which receives two arguments, $day_difference and $scheduled_time:
function decide($day_difference, $scheduled_time)
{
if($scheduled_time == 'evening')
{
return $day_difference > 0;
}
else
{
return $day_difference == 0;
}
}
And use it like so:
if( decide($day_difference, $scheduled_time) )
{
echo "something";
}
else
{
echo "h";
}
according to your requirements this can be done using the PHP eval() function which i don't recommend using it only when necessary.
you can check When is eval evil in php?
you can use the below script instead:
if( $sheduled_time == 'evening' && $diff > 0 )
{
echo "This is the Evening and the Difference is Positive";
}
else if($diff == 0)
{
echo "This is not evening";
}
Thankyou for helping me solve my question
I solved this in another way
$day_difference = "some integer value";
$var1 = false ;
if($sheduled_time == 'evening_before'){
if($day_difference > 0 ){
$var1 = true ;
}
}else{
if($day_difference == 0 ){
$var1 = true ;
}
}
if($var1 === true){
echo "something";
}else{
echo "h";
}

PHP Conditional > how to know what didn't match?

if i have statement:
$a = 1;
$b = 2;
$c = 3;
if($a == 1 && $b == 2 && $c == 3)
{
echo 'correct';
}
else
{
echo 'what variable's weren't matched';
}
Is there any way of knowing what didn't watch instead of writing everything separately?
Cheers!
No. Your expression was turned into a boolean, so apart from checking the equality(s) again you cannot find out which triggered the "false".
You need to test each individually, but you could do something like this:
$a = 1;
$b = 2;
$c = 3;
$a_matched = $a == 1;
$b_matched = $b == 1;
$c_matched = $c == 1;
if($a_matched && $b_matched && $c_matched)
{
echo 'correct';
}
else
{
if (!$a_matched) echo 'a did not match!';
if (!$b_matched) echo 'b did not match!';
if (!$c_matched) echo 'c did not match!';
}
but that's less clear than just:
$a = 1;
$b = 2;
$c = 3;
if($a == 1 && $b == 2 && $c == 3)
{
echo 'correct';
}
else
{
if (!$a == 1) echo 'a did not match!';
if (!$b == 2) echo 'c did not match!';
if (!$c == 3) echo 'b did not match!';
}
Actually, heh, I take back my comment. You can rely on the boolean short-circuiting to set a variable indicating the last part of the conditional which was true:
if (($x = 'a') && $a == 1 && ($x = 'b') && $b == 2 && ($x = 'c') && $c == 3) {
echo "correct\n";
} else {
echo "$x is wrong\n";
}
Note, I would never write this in production code because it's goofy and very hard to understand what's supposed to be going on. But fun to fiddle with, at least.
Nope! That's not possible. You can make life a lot simpler by using arrays, though:
$results = array(1, 2, 4);
$expected = array(1, 2, 3);
$count = count($results);
$wrong = array();
for($i = 0; $i < $count; $i++) {
if($results[$i] !== $expected[$i]) {
$wrong[] = $i;
}
}
if(count($wrong) > 0) {
echo "There were wrong ones. They were at positions: " . implode(', ', $wrong);
} else {
echo "All good!";
}
For example.

Categories