[Solved] Type-casting to boolean (2024)

php casting boolean

43,681

Solution 1

It's actually not as strange it seems. (bool) has higher precedence than ==, so this:

var_dump((bool) 1==2);

is equivalent to this:

var_dump( ((bool) 1) == 2);

or this:

var_dump(true == 2);

Due to type juggling, the 2 also essentially gets cast to bool (since this is a "loose comparison"), so it's equivalent to this:

var_dump(true == true);

or this:

var_dump(true);

Solution 2

Because in the first example, the cast takes place before the comparison. So it's as if you wrote

((bool) 1)==2

which is equivalent to

true == 2

which is evaluated by converting 2 to true and comparing, ultimately producing true.

To see the expected result you need to add parens to make the order explicit:

var_dump((bool)(1==2));

See it in action.

Solution 3

I use this way:

!!0 (false)!!1 (true)

Solution 4

filter_var - Filters a variable with a specific filter

$boolvar = filter_var('true', FILTER_VALIDATE_BOOLEAN);

boolval - Get the boolean value of a variable PHP 5 >=

$boolvar = boolval ('true');

And literally with a ternary operator but I can't recommend it

$boolvar = ($string === 'true') ? true: false; 

View more solutions

Share:

43,681

Related videos on Youtube

[Solved] Type-casting to boolean (1)

13 : 53

Boolean Java Tutorial

Alex Lee

143654

[Solved] Type-casting to boolean (2)

04 : 53

The boolean Data Type in Java

Neso Academy

44676

[Solved] Type-casting to boolean (3)

08 : 14

Using Boolean in Python (Python Tutorial #11)

[Solved] Type-casting to boolean (4)

11 : 10

005 Python Data Type Conversions |type casting | int, |string, |float, | Boolean | list etc.

Pro Geomatics

102

[Solved] Type-casting to boolean (5)

05 : 50

Java Type Casting Tutorial

Alex Lee

69

[Solved] Type-casting to boolean (6)

10 : 44

Data Type Part1 (boolean, integer, float and string) and Type Casting In Python

Obieda Ananbeh

61

[Solved] Type-casting to boolean (7)

07 : 15

C# type casting 💱

Bro Code

5

[Solved] Type-casting to boolean (8)

13 : 08

Booleans for Recruiters - How To Write A Boolean Search

Tyler Talks

3

[Solved] Type-casting to boolean (9)

09 : 17

Lesson 9 : Datatypes - Type Casting - Array - Boolean - Integer - Object - Float - String

Ahmed Fathi

2

[Solved] Type-casting to boolean (10)

12 : 31

Python Tutorial || Type Casting: bool() and str() functions|| by Durga Sir

Durga Software Solutions

2

[Solved] Type-casting to boolean (11)

01 : 02

Type-casting to boolean - PHP

Solutions Cloud

[Solved] Type-casting to boolean (12)

Author by

Paris Liakos

Updated on July 09, 2022

Comments

  • [Solved] Type-casting to boolean (13)

    Paris Liakos almost 2 years

    Can someone explain me why this:

    var_dump((bool) 1==2);

    returns

    bool(true)

    but

    var_dump(1==2);

    returns

    bool(false)

    Of course the second return is correct, but why in the first occasion php returns an unexpected value?

    • [Solved] Type-casting to boolean (14)

      Brad over 12 years

      Order of operations is getting you here...

  • [Solved] Type-casting to boolean (15)

    Paris Liakos over 12 years

    Thanks!very detailed explanation:)

  • [Solved] Type-casting to boolean (16)

    Markus Zeller about 8 years

    As the headline asks for typecasting this answer is correct and can be used in almost any language. This construct is great for languages like JavaScript where you need a real "true" or "false", but not to keep the original value. BTW, typecasting with (bool) is a little bit faster.

  • [Solved] Type-casting to boolean (17)

    xDaizu over 7 years

    ...yet another reason to try to always use ===

  • [Solved] Type-casting to boolean (18)

    dougd_in_nc over 6 years

    @xDaizu This doesn't have anything to do with using ===. The following returns false, which is still unexpected if you don't understand operator precedence: (bool) 1===1 Simply use == and === when each is appropriate for the given situation. Not just based on some "always do this" rule.

  • [Solved] Type-casting to boolean (19)

    ruakh over 6 years

    @dougd_in_nc: You're right that (bool) 1===1 has a similar problem to (bool) 1==2, but === does eliminate half of what's confusing here: the type juggling rules are complicated and counterintuitive. I'm not aware, personally, of any situation where == is appropriate, but I guess that's a matter for a different question . . .

  • [Solved] Type-casting to boolean (20)

    dougd_in_nc over 6 years

    @ruakh with regard to the question, I don't find the expression 1==2 confusing at all and I'm aware of several situations where == works very well. Again, == vs. === is irrelevant to finding a solution to the given problem. Type juggling has nothing to do with the problem that the OP is presenting. It's just confusing this with a separate issue.

  • [Solved] Type-casting to boolean (21)

    ruakh over 6 years

    @dougd_in_nc: Re: "I don't find the expression 1==2 confusing at all": But the OP's code didn't have the expression 1==2, it had the equivalent of true==2. Do you really claim to find it obvious that true==2 should be true? Re: "I'm aware of several situations where == works very well": Ah, but are you aware of any situations where it's better than ===? If not, then a "never use ==, only ===" rule is actually a pretty good one.

  • [Solved] Type-casting to boolean (22)

    dougd_in_nc over 6 years

    The OP code has var_dump((bool) 1==2); It's the equivalent of true == 2 because of the OPERATOR PRECEDENCE. Just like ((bool) 1===1) is equivalent to (true === 1)... That's certainly not obvious the way it's written, even with ===. Also, true==2 isn't hard to understand for me, and makes perfect sense for some applications. However, if anyone doesn't understand == well enough to use it, then I can understand why they would want to always use ===. So, to each his own.

  • [Solved] Type-casting to boolean (23)

    Daniel Wu over 3 years

    @dougd_in_nc If OP used === in the first statement, he's going to get bool(false) as he wanted, because true is not the same as 2.

  • [Solved] Type-casting to boolean (24)

    dougd_in_nc over 3 years

    @DanielWu yes, you found one of the many ways to change an expression to evaluate false. The poster wasn't asking "how can I make this expression return false." If the poster just wanted to find a way to get false, I'm sure they could do that by themselves

Recents

Why Is PNG file with Drop Shadow in Flutter Web App Grainy?

How to troubleshoot crashes detected by Google Play Store for Flutter app

Cupertino DateTime picker interfering with scroll behaviour

Why does awk -F work for most letters, but not for the letter "t"?

Flutter change focus color and icon color but not works

How to print and connect to printer using flutter desktop via usb?

Critical issues have been reported with the following SDK versions: com.google.android.gms:play-services-safetynet:17.0.0

Flutter Dart - get localized country name from country code

navigatorState is null when using pushNamed Navigation onGenerateRoutes of GetMaterialPage

Android Sdk manager not found- Flutter doctor error

Flutter Laravel Push Notification without using any third party like(firebase,onesignal..etc)

How to change the color of ElevatedButton when entering text in TextField

[Solved] Type-casting to boolean (2024)

FAQs

How do you cast to a boolean? ›

You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types.

How do you convert data type to boolean? ›

You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL .

How do you convert to bool in TypeScript? ›

One of the simplest ways to convert a string to a boolean value in TypeScript is by using the Boolean() function. The Boolean() function takes a value as an argument and returns the corresponding boolean representation of that value.

How to convert a string into a boolean? ›

To convert String into Boolean object, we can use Boolean. valueOf(string) method which returns instance of Boolean class. To get boolean true, string must contain "true". Here, case is ignored.

Can we type cast int to Boolean? ›

You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.

What is Boolean casting? ›

A boolean is a primitive value that represents either true or false. In Boolean contexts, JavaScript utilizes type casting to convert values to true/false. There are implicit and explicit methods to convert values into their boolean counterparts.

How do you convert numeric to boolean? ›

tf = boolean( X ) converts the numeric expression X into a Boolean value. If the expression evaluates to zero, boolean returns logical 0 ( false ).

How do you turn an object into a boolean? ›

You can use the Boolean() constructor to create a boolean object and then use its valueOf property to get the primitive boolean value. It takes in a value to convert to a boolean. If the value is falsy it will return false . If the value is truthy , it will return true .

How do you create a boolean? ›

If you want to define a boolean in Python, you can simply assign a True or False value or even an expression that ultimately evaluates to one of these values. You can check the type of the variable by using the built-in type function in Python.

How to convert query string to boolean in JavaScript? ›

JavaScript Convert a string to boolean
  1. Approach 1: Using JavaScript == Operator.
  2. Approach 2: Using JavaScript === Operator.
  3. Approach 3: Using the Boolean() function.
  4. Approach 4: Using a regular expression.
  5. Approach 5: Using the !! (double negation) operator.
  6. Approach 6: Using JSON.parse()
  7. Approach 7: Using Ternary Operator.
May 28, 2024

How do you assign a value to a boolean in TypeScript? ›

Boolean is the data type that can contain only one of two possible values: true or false . In TypeScript, we can use either let or const to assign a Boolean value to a variable, like we do in JavaScript. As you can see, you can change the Boolean value for the variable start .

How to convert boolean to text in JavaScript? ›

toString() . For Boolean values, the toString method returns a string representation of the boolean value, which is either "true" or "false" . The toString() method requires its this value to be a Boolean primitive or wrapper object.

How do you return a string in a boolean method? ›

The Java Boolean toString(boolean) returns a String object representing the specified boolean. If the specified boolean is true, then the string "true" will be returned, otherwise the string "false" will be returned.

How do you convert a string to a boolean array? ›

Ways to Convert Python String to Boolean
  1. Using Bool()
  2. Using Eval()
  3. Using List Comprehension.
  4. Using Map()
  5. Using ast. literal_eval()
  6. Using Dictionary.
Mar 14, 2024

Can you cast boolean to string? ›

A BOOLEAN value can be cast explicitly to any of the string types. The result is 'true', 'false', or null.

How do you enter a boolean? ›

boolean user = true;

So instead of typing int or double or string, you just type boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false. Notice that the assignment operator is a single equals sign ( = ).

How do you convert a number to a boolean? ›

We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e. “false” or “true”.

How to cast string to boolean in JavaScript? ›

The Solution. You can use an equality operator, Boolean() constructor, or the double NOT ( !! ) operator to convert a “true” or “false” string to a boolean.

How to cast boolean in Java? ›

In Java, use Boolean. parseBoolean(string) to convert a String to a boolean. However, use the Boolean. valueOf(string) method if you wish to convert a String to a Boolean object function.

References

Top Articles
How to Visit the Amalfi Coast on a Budget - Dollar Flight Club
Jonathan Cahn Israel Tour 2024
Tripadvisor Antigua Forum
Wnem Radar
Cecil Burton Funeral Home | Shelby, North Carolina
Ssm Health Workday App
Oklahoma Dam Generation Schedule
Petco Westerly Ri
Craigslist Greencastle
Stolen Touches Neva Altaj Read Online Free
SSD an SATA Anschluss bei Futro S920
Evil Dead Rise Showtimes Near Amc Antioch 8
80 For Brady Showtimes Near Cinemark At Harlingen
Ups Cc Center
Nook Glowlight 3 Case
Craigslist Worcester Massachusetts: Your Guide to the City's Premier Marketplace - First Republic Craigslist
Craigslist Cars And Trucks For Sale Private Owners
M&T Bank Atm Locations Near Me
Courierpress Obit
Tinyzonetv.to Unblocked
Pokemon Fire Red Download Pc
Sam's Club Key Event Dates 2023 Q1
Circloo Unblocked
Synergy Grand Rapids Public Schools
Unblocked WTF, UBG9 Unblocked Games, UBGWTF Games, Unblocked WTF, WTF Games Unblocked
Tuition Fee Compensation
Minneapolis, MN Real Estate & Homes for Sale | realtor.com®
Kagtwt
modelo julia - PLAYBOARD
Toernooien, drives en clubcompetities
Monkey Werx Sitrep 2022
Kaelis Dahlias
Wall Tapestry At Walmart
Cluster Truck Unblocked Wtf
Conner Westbury Funeral Home Griffin Ga Obituaries
Kobe Express Bayside Lakes Photos
Aig Cyberedge Policy Wording
Terraria Water Gun
Ben Rickert Net Worth
Sierra Vista Jail Mugshots
Boostmaster Lin Yupoo
Patriot Ledger Obits Today
Ohio State Football Wiki
Urgent Care Pelham Nh
Smartmove Internet Provider
Motorcycle Sale By Owner
Katmovie.hs
Houses For Sale 180 000
Maria Butina Bikini
Towne Pizza Carman Road
Ladyva Is She Married
The Emperor's New Groove | Rotten Tomatoes
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 6186

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.