[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 (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)

References

Top Articles
Hannah Pukis Leak
Tugboat Information
Walgreens Pharmqcy
1970 Chevelle Ss For Sale Craigslist
EY – все про компанію - Happy Monday
craigslist: south coast jobs, apartments, for sale, services, community, and events
Here's how eating according to your blood type could help you keep healthy
Find your energy supplier
Craigslist Heavy Equipment Knoxville Tennessee
Pro Groom Prices – The Pet Centre
Washington, D.C. - Capital, Founding, Monumental
Robert Malone é o inventor da vacina mRNA e está certo sobre vacinação de crianças #boato
Stihl Km 131 R Parts Diagram
ᐅ Bosch Aero Twin A 863 S Scheibenwischer
Napa Autocare Locator
Uktulut Pier Ritual Site
Missouri Highway Patrol Crash
Metro Pcs.near Me
Big Lots Weekly Advertisem*nt
Mega Personal St Louis
Tips and Walkthrough: Candy Crush Level 9795
Bennington County Criminal Court Calendar
MyCase Pricing | Start Your 10-Day Free Trial Today
Del Amo Fashion Center Map
Myql Loan Login
Delectable Birthday Dyes
Dove Cremation Services Topeka Ks
Water Temperature Robert Moses
Biografie - Geertjan Lassche
The Creator Showtimes Near Baxter Avenue Theatres
R3Vlimited Forum
Jambus - Definition, Beispiele, Merkmale, Wirkung
MethStreams Live | BoxingStreams
Att U Verse Outage Map
Prima Healthcare Columbiana Ohio
Etowah County Sheriff Dept
Why Holly Gibney Is One of TV's Best Protagonists
دانلود سریال خاندان اژدها دیجی موویز
Dmitri Wartranslated
Cherry Spa Madison
What Is Kik and Why Do Teenagers Love It?
Casamba Mobile Login
Ferguson Showroom West Chester Pa
Celsius Claims Agent
Lady Nagant Funko Pop
Beds From Rent-A-Center
Lesly Center Tiraj Rapid
Ephesians 4 Niv
Image Mate Orange County
Skyward Login Wylie Isd
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Swissport Timecard
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5629

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.