-3

I have to store a binary value in a variable or an array element, to indicate that an option is enabled or disabled.

I believe using "Yes" or "No" is less efficient than 1 or 0 (or empty), but I wonder whether there's any difference between 1/0 and TRUE/FALSE, in terms of performance or memory usage or anything else.

Between

$option = 1; # if the option is enabled
$option = 0; # if the option is disabled OR
$option = ""; # if the option is disabled

and

$option = TRUE; # if the option is enabled
$option = FALSE; # if the option is disabled

which way is recommended? Why?

Thanks.

msoutopico
  • 357
  • 3
  • 15
  • 3
    Have you performed any benchmarking yourself? – Jay Blanchard Dec 04 '17 at 20:11
  • 1
    No practical difference whatsoever. If for some unimaginable reason 1/0 is better, surely PHP would trivially optimize by handling boolean values internally as integers. – JJJ Dec 04 '17 at 20:13
  • 2
    Never use strings like "yes" and "no" or "true" and "false" to store binary values. Always use a format which correctly evaluates in a boolean context. E.g., `(string) "false"` is true, so you don't want to use that. – Alex Howansky Dec 04 '17 at 20:14
  • Thank you for your comments. I didn't do benchmarking, but I did some research and didn't find answers. Doing benchmarking can be a good idea but I'm not sure how to do that other than checking how long it takes to run the script in the browser. However, on other occasions I have seen that it's quite variable without changing anything in the script. – msoutopico Dec 05 '17 at 09:41
  • Alex confirms that strings are not a good idea, and I understand from JJJ's answer that TRUE/FALSE and 1/0 would be pretty much equivalent. In fact, I've seen that SQLite turns TRUE/FALSE values to 1/0 when inserting data. If using 1/0 integers, I'm still not sure, though, whether 0, NULL and "" (empty string) would be equivalent, when the value is not 1. – msoutopico Dec 05 '17 at 09:44

2 Answers2

1

In the 'Anything else' category; a human will immediately understand if option is a Boolean type from Yes/No/True/False/On/Off, but not from 0/1, which can be a numerical option as well. This issue can be remedied by naming the option with suffix like _bool that indicates that it is a Boolean option and not an Integer option, this is then visible and obvious both in the code and any possible configuration file for options.

Doege
  • 341
  • 4
  • 12
0

This answer1 suggests that zero, null and empty are equivalent, and this answer2 suggests that 1 and true are equivalent.

msoutopico
  • 357
  • 3
  • 15