Convert boolean to integer value php

前端 未结 7 1640
广开言路
广开言路 2021-02-04 23:58

Is there any builtin function for PHP that will take a boolean value and return its integer equivalent? 0 for FALSE, 1 for TRUE? Of course you can easily create a function to do

相关标签:
7条回答
  • 2021-02-05 00:25

    If you are unsure of the data type see the example below, it works on strings, integers and booleans.

    <?php
    
    $options = [ TRUE, FALSE, 'true', 'false', 1, 0, '1', '0', 'on', 'off', 'yes', 'no' ];
    
    foreach ( $options as $option ) {
        $bool = filter_var( $option, FILTER_VALIDATE_BOOLEAN ); // TRUE or FALSE
        print (int) $bool . ' '; // 1 or 0
    } 
    // Outputs: 1 0 1 0 1 0 1 0 1 0 1 0 
    
    ?>
    

    filter_var( $var, FILTER_VALIDATE_BOOLEAN ) will return bool(true) or bool(false) then simply cast as integer.

    filter_var()

    (PHP 5 >= 5.2.0, PHP 7)

    filter_var — Filters a variable with a specified filter

    0 讨论(0)
提交回复
热议问题