1

I have a problem with the way php saves data in mongoDB. I have a .csv file in which I have a field that has to be boolean, so I put 'false' for it. When I read it with php from .csv, the value is a 'string', which is interpreted by mongoDB as an NOT-empty string, which results in a 'true' value field. Is there a way to read it like a boolean value?

I found an answer that will partially solve my problem (How to convert string to boolean php), but I want to avoid that part and read it like bool, or at least save it like a bool in mongoDB with the values 'false' => false, and not 'false' => true

Community
  • 1
  • 1
M. Marc
  • 512
  • 6
  • 25
  • If you want to read a string containing a word like `'true'` or `'false'` and treat it as an actual Boolean value, then __you__ have to provide the magic that will convert it to an actual boolean value.... you can't avoid it.... PHP doesn't have that "magic" built-in.... and it's not as if it's difficult for you to do – Mark Baker Jan 12 '16 at 08:13
  • well, if I use boolval('false') ==> true which is not what I expect, and I don't want to use the solutions given in the article I gave in the question. But if there is no other option, I'll do the best with what I have. – M. Marc Jan 13 '16 at 08:50
  • `'false'` is a string containing an English language word that has no special meaning as a string in PHP, likewise a string containing the English language word `'true'` has no special meaning as a string in PHP either.... they're just strings, sequences of characters, treated in PHP in the same way as any other string is treated; they only have special meaning to you as a human being.... and this means that functions like `boolval()` just treat it as a sequence of characters with no special meaning – Mark Baker Jan 13 '16 at 10:05

1 Answers1

1

A simple but dirty fix is to check the value and appoint a boolean accordingly.

$var = (var === 'true') ? true : false;

Or you could even make an array with possibilities.

$var = (in_array($string, array('1', 'true', true))) ? true : false;

I know this is not a perfect solution but it will work nontheless.

After more research

I've done some more reading and found out that you can also use the FILTER_VALIDATE_BOOLEAN filter.

// This will return either true or false
$var = filter_var($csvValue, FILTER_VALIDATE_BOOLEAN);
Peter
  • 8,776
  • 6
  • 62
  • 95
  • thanks, but the filter_var() solution doesn't work like I want. And I want to avoid the first two transformation you gave As I said, I will do the best with what I have. – M. Marc Jan 13 '16 at 08:51