1
\$\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.
}
?>
asked Oct 10, 2011 at 9:51
\$\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

answered Oct 10, 2011 at 9:54
\$\endgroup\$
3
  • \$\begingroup\$ If you look into the code, MEMBER_LIMIT is always defined. \$\endgroup\$ Commented Oct 10, 2011 at 9:58
  • \$\begingroup\$ Indeed, I thought the user may comment back in the initial line however \$\endgroup\$ Commented 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\$ Commented Oct 10, 2011 at 10:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.