Convert String 'true' or 'false' to interger '1' or '0' - php

I want to convert String variable 'true' or 'false' to int '1' or '0'.
To achieve this I'm trying like this
(int) (boolean) 'true' //gives 1
(int) (boolean) 'false' //gives 1 but i need 0 here
I now I can using array like array('false','true');
or using if($myboolean=='true'){$int=1;}
But this way is less efficient.
Is there another more efficient way like this (int) (boolean) 'true' ?
I know this question has been asked. but I have not found the answer

Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP.
Depending on your needs, you should consider using filter_var() with the FILTER_VALIDATE_BOOLEAN flag.
(int)filter_var('true', FILTER_VALIDATE_BOOLEAN);
(int)filter_var('false', FILTER_VALIDATE_BOOLEAN);

Why not use unary operator
int $my_int = $myboolean=='true' ? 1 : 0;

the string "false" is truthy. That's why (int) (boolean) "false" return 1 instead of 0. If you want to get a false boolean value from a string, you can pass an empty string (int) (boolean) "". More info here.

PHP
$int = 5 - strlen($myboolean);
// 5 - strlen('true') => 1
// 5 - strlen('false') => 0
JAVASCRIPT
// ---- fonction ----
function b2i(b){return 5 - b.length}
//------------ debug -----------
for(b of ['true','True','TRUE','false','False','FALSE'])
{
console.log("b2i('"+b+"') = ", b2i(b));
}

Try this:
echo (int) (boolean) '';

$variable = true;
if ($variable) {
$convert = 1;
}
else {
$convert = 0;
}
echo $convert

Normally just $Int = (int)$Boolean would work fine, or you could just add a + in front of your variable, like this:
$Boolean = true;
var_dump(+$Boolean);
ouputs: int(1);
also, (int)(bool)'true' should work too

Related

How to convert boolean to string at query binding?

In repository, I built a query and I want to bind value, but I need to convert the $isAllowed boolean value to a string ('true', 'false' or 'null'). How to do it in the right way?
':isAllowed' => $isAllowed,
You can just do :
':isAllowed' => $isAllowed ? 'true' : 'false'
Check ternary operator here:
https://www.php.net/manual/en/language.operators.comparison.php
You can assign a new variable or use an existing one like this:
$isAllowed_str = $isAllowedBool ? 'true' : 'false';
For NULL value, it should be considered false:
When converting to bool, the following values are considered false:
the boolean false itself
the integer 0 (zero)
the floats 0.0 and -0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.
Source: https://www.php.net/manual/en/language.types.boolean.php
If you need to separate null value you could check with an if statement before casting bool to str:
if(is_null(isAllowedBool)) {
$isAllowed_str = "NULL";
}
else {
$isAllowed_str = $isAllowedBool ? 'true' : 'false';
}
This will do what you want.
':isAllowed' => json_encode($isAllowed),
Example
json_encode(true); // = 'true'
json_encode(false); // = 'false'
json_encode(null); // = 'null'

Variable with value 0 equal string results in true

I have acrossed some really weird behaviour in PHP statment when having example below:
Logically it shouldn't return 1 in this context. Why this is happening ? Just was wondering.
$test = 0;
var_dump($test); // gives int 0
$test = ($test == 'test') ? 1 : 0;
var_dump($test); //gives int 1
This is because of type juggling. 'test' is equal to 0 because (int)'test' actually is 0. Thus, your condition is true and 1 is the result.
In your particular case you may want to know how PHP converts strings to numbers.
Just try with === to compare also type of values:
$test = ($test === 'test') ? 1 : 0;

How to correctly parse an integer in PHP?

I can use intval, but according to the documentation:
Strings will most likely return 0 although this depends on the
leftmost characters of the string. The common rules of integer casting
apply.
... and the value to parse can be 0, that is I will not able to distinguish between zero and a string.
$value1 = '0';
$value2 = '15';
$value3 = 'foo'; // Should throw an exeption
Real question is: how can I parse the string and distinguish between a string that cast to 0 and a zero itself?
In the code below, $int_value will be set to null if $value wasn't an actual numeric string (base 10 and positive), otherwise it will be set to the integer value of $value:
$int_value = ctype_digit($value) ? intval($value) : null;
if ($int_value === null)
{
// $value wasn't all numeric
}
I have not benchmarked against the ctype_digit(), but I think the following is a nice option. Of course it depends on the exact behavior you expect.
function parseIntOrException($val) {
$int = (int)$val;
if ((string)$int === (string)$val) {
throw \Exception('Nope.');
}
return $int;
}
http://3v4l.org/Tf8nh
1 1
'2' 2
'3.0' false
4.0 4
5 5

php variables comparison == vs ===

this is code:
$s = 0;
$d = "dd";
if ($s == $d) {
var_dump($s);
die(var_dump($d));
}
result is:
int 0
string 'dd' (length=2)
Please explain why.
why ($s == $d) results as true?
Of course, if === is used it will results as false but why this situation requires ===?
Shouldn't it be returned false in both situations?
Because (int)$d equals with 0 and 0=0
you must use strict comparison === for different character tyes (string) with (int)
Your $d is automatically converted to (int) to have something to compare.
When you compare a number to a string, the string is first type juggled into a number. In this case, dd ends up being juggled into 0 which means that it equates to true (0==0).
When you change the code to:
<?php
$s = 1;
$d = "dd";
if ($s == $d)
{
var_dump($s);
die(var_dump($d));
}
?>
You will find that it doesn't pass the if statement at all.
You can more details by reading up on comparison operators and type juggling.
The string "dd" is converted to int, and thus 0.
Another example :
if ( "3kids" == 3 )
{
return true;
}
And yes, this returns true because "3kids" is converted to 3.
=== does NOT auto convert the items to the same type.
Also : 0 == false is correct, but 0 === false is not.
See : http://php.net/manual/en/language.types.type-juggling.php
The string will try to parsed into a number, returns 0 if it is not in right number format.
As seen in the php website :
http://php.net/manual/en/language.operators.comparison.php
var_dump(0 == "a"); // 0 == 0 -> true
In PHP, == should be pronounce "Probably Equals".
When comparing with ==, PHP will juggle the file-types to try and find a match.
A string with no numbers in it, is evaluated to 0 when evaluated as an int.
Therefore they're equals.

PHP Type-Cast Confusion

I have the following code:
<?php
$val = 0;
$res = $val == 'true';
var_dump($res);
?>
I always was under impression that $res should be 'false' as in the above expression PHP would try to type cast $val to boolean type (where zero will be converted as false) and a string (non-empty string is true). But if I execute the code above output will be:
boolean true
Am I missing something? Thanks.
In PHP, all non-empty, non-numeric strings evaluate to zero, so 0 == 'true' is TRUE, but 0 === 'true' is FALSE. The string true has not been cast to a boolean value, but is being compared as a string to the zero. The zero is left as an int value, rather than cast as a boolean. So ultimately you get:
// string 'true' casts to int 0
0 == 0 // true
Try this:
echo intval('true');
// 0
echo intval('some arbitrary non-numeric string');
// 0
Review the PHP type comparisons table. In general, when doing boolean comparisons in PHP and types are not the same (int to string in this case), it is valuable to use strict comparisons.
Because $val is the first operator PHP converts the string true to an integer which becomes 0. As a result 0 ==0 and your result is true;
Try this
<?php
$val = 1;
$res = (bool)$val == 'true';
var_dump($res);
?>

Categories