E. Henry
E. Henry

Reputation: 21

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.

Upvotes: 0

Views: 151

Answers (4)

Progrock
Progrock

Reputation: 7485

<?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.

Upvotes: 0

BNT
BNT

Reputation: 994

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.

Upvotes: 0

TarangP
TarangP

Reputation: 2738

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";
}

Upvotes: 0

Sofyan Thayf
Sofyan Thayf

Reputation: 1328

<?php
if ( (condition1 && ($a > $b*0.5)) || (!condition1 && ($a > $b))  ) {
  echo "successful"; 
else {
  echo "missed";
}
?>

Upvotes: 3

Related Questions