0
\$\begingroup\$

So, I wanted to avoid an

if (...) { }
else if (...) { }
else { }

scenario to avoid duplicating code. After a little playing, I got the following working (works from the testing i've done). Am wondering if anyone has any feedback on this approach or suggestions on on possible improvement?

Sometimes I think I know what I'm doing, sometimes I don't.

<?php

  // define("MEMBER_LIMIT",0); // no member limit
defined("MEMBER_LIMIT",100); // limit to 100 ppl in group

  // $memcount is set via sn SQL query
$memcount = 9; // number of people currently in group (let's say).

if (!defined("MEMBER_LIMIT") ||
 ((defined("MEMBER_LIMIT") && MEMBER_LIMIT == 0) || 
  (MEMBER_LIMIT > 0 && $memcount>0 && $memcount < MEMBER_LIMIT))) {
  // will do something
}
else {
  // will do something else.
}
?>
\$\endgroup\$
0

1 Answer 1

7
\$\begingroup\$

How about:

if (!defined("MEMBER_LIMIT") ||  MEMBER_LIMIT == 0 || $memcount < MEMBER_LIMIT) {
  // will do something
}
else {
  // will do something else.
}

The key is to look for both complementary (multiple items that accomplish the same thing by different means) and contradicting criteria (which would interrupt your desired flow of logic) in if statements

\$\endgroup\$
3
  • \$\begingroup\$ If you look into the code, MEMBER_LIMIT is always defined. \$\endgroup\$
    – hakre
    Oct 10, 2011 at 9:58
  • \$\begingroup\$ Indeed, I thought the user may comment back in the initial line however \$\endgroup\$
    – Ergo Summary
    Oct 10, 2011 at 9:59
  • \$\begingroup\$ yes, if i leave 'defined(...)' in there. there are plans to have certain things defined and others not, which i was the !defined(...) check. \$\endgroup\$
    – coelmay
    Oct 10, 2011 at 10:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.