1
votes

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

1
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
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
'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

1 Answers

1
votes

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);