is_bool
is_bool(mixed $value): bool
Finds whether a variable is a boolean.
C C23
#include <stdbool.h>
#include <stdio.h>
#define is_bool(x) _Generic((x), _Bool: 1, default: 0)
int main(void) {
bool b = true;
int i = 1;
printf("%d %d %d\n", is_bool(b), is_bool(i), is_bool("true"));
return 0;
}
1 0 0
C++ C++26
#include <iostream>
#include <type_traits>
int main() {
bool b = true;
int i = 1;
std::cout << std::boolalpha << std::is_same_v<decltype(b), bool> << " "
<< std::is_same_v<decltype(i), bool> << "\n";
return 0;
}
true false
C# v11.0.100
object[] xs = { true, 1, "true" };
foreach (object x in xs) {
Console.WriteLine(x is bool);
}
True False False
Go v1.27.4
package main
import "fmt"
func main() {
xs := []any{true, 1, "true"}
for _, x := range xs {
_, ok := x.(bool)
fmt.Println(ok)
}
}
true false false
Java v27.0.1
public class Main {
public static void main(String[] args) {
Object[] xs = { true, 1, "true" };
for (Object x : xs) {
System.out.println(x instanceof Boolean);
}
}
}
true false false
JavaScript v26.13.1
console.log([typeof true === "boolean", typeof 1 === "boolean", typeof "true" === "boolean"]);
[ true, false, false ]
PHP v8.6.0
echo json_encode([is_bool(true), is_bool(1), is_bool("true")]);
[true,false,false]
Python v3.15.2
print([isinstance(x, bool) for x in [True, 1, "true"]])
[True, False, False]
Rust v1.99.1
use std::any::Any;
fn main() {
let xs: Vec<Box<dyn Any>> = vec![Box::new(true), Box::new(1i32), Box::new("true")];
for x in &xs {
println!("{}", x.is::<bool>());
}
}
true false false
TypeScript v26.13.1
const xs: (boolean | number | string)[] = [true, 1, "true"];
console.log(xs.map((x) => typeof x === "boolean"));
[ true, false, false ]
Language differences
C: since C99, bool (a macro for _Bool) and int are distinct types, distinguishable with _Generic.
C++: bool is its own fundamental type.
C#: the idiomatic counterpart on dynamic containers is is bool.
Go: the idiomatic counterpart on dynamic containers is the assertion .(bool).
Java: the idiomatic counterpart on dynamic containers is instanceof Boolean.
JavaScript: subtler — 1 == true holds (loose comparison coerces to number), typeof 1 is "number" while typeof true is "boolean", and the strict 1 === true fails.
PHP: the relationship between 1 and true is the core difference — the loose 1 == true holds yet is_bool(1) is false (type-strict).
Python: leans the other way — bool subclasses int, so True == 1 and even True + True == 2; isinstance(1, bool) is false but isinstance(True, int) is true; functions that accept only booleans should check isinstance(x, bool), and functions accepting integers must realize booleans sneak in.
Rust: the idiomatic counterpart on dynamic containers is Any::is::<bool>().