Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

PHP string to boolean

Featured Replies

Having a bit of a mental block. Is it possible to convert a string to a boolean in PHP? Typecasting to int always returns 0 whereas bool always returns 1.

 

$string1 = "true";
$string2 = "false";

echo (bool)$string1, " | ", (bool)$string2;
echo "<br />";
echo (int)$string1, " | ", (int)$string2;

 

outputs:

1 | 1
0 | 0

 

I know I can use conditions but I was wondering if theres a quick way to do it.

 

Cheers

No, thats the expected result when type juggling those values. You'd need to use a conditional statement to return a boolean from those strings. The only thing php will convert to a boolean from string is '0' and '' for false, anything else will be cast as true.

No, thats the expected result when type juggling those values. You'd need to use a conditional statement to return a boolean from those strings. The only thing php will convert to a boolean from string is '0' and '' for false, anything else will be cast as true.

 

He's right, you know - I just checked. Ha.

 

I'd set up an Orwellian true = false example if I could be arsed.

  • 2 months later...

Having a bit of a mental block. Is it possible to convert a string to a boolean in PHP? Typecasting to int always returns 0 whereas bool always returns 1.

 

$string1 = "true";
$string2 = "false";

echo (bool)$string1, " | ", (bool)$string2;
echo "<br />";
echo (int)$string1, " | ", (int)$string2;

 

outputs:

1 | 1
0 | 0

 

I know I can use conditions but I was wondering if theres a quick way to do it.

 

Cheers

 

 

This is what I do...

$str = 'false';

$bool = ($str == 'true');

//proof
echo ($bool)? 'Boolean TRUE' : 'Boolean FALSE';

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.