Convert boolean to integer value php

前端 未结 7 1639
广开言路
广开言路 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:01

    If you are getting your value in from JSON I.E. Via an AJAX POST, the value will come in as a string (As you have found). A way around this is to compare the true/false string and then cast the bool to an int

    $requestBool = $_REQUEST['bool_value']; //This is 'true' or 'false'
    
    $myInt = (int)($requestBool === 'true');
    echo $myInt;
    
    //returns: 0 or 1
    
    0 讨论(0)
  • 2021-02-05 00:06

    http://www.php.net/manual/en/language.types.integer.php

    Normally, simply $myInt = (int)$myBoolean should work, can you show us your code otherwise ?

    0 讨论(0)
  • 2021-02-05 00:14

    Just add a "+" before your variable like this :

    $myBool = true; 
    
    var_dump(+$myBool);
    
    ouputs: int(1);
    
    0 讨论(0)
  • 2021-02-05 00:14

    You can do multiple castings in a single go:

    $isTest = 'true';
    
    (int)(bool)$isTest
    
    echo $isTest; // this outputs 1
    
    0 讨论(0)
  • 2021-02-05 00:16

    Use type casting (bool):

    var_dump((bool) 1);         // bool(true)
    var_dump((bool) 0);         // bool(false)
    
    0 讨论(0)
  • 2021-02-05 00:21
    // cast to Integer
    echo (int)true;         // 1
    echo (int)false;        // 0
    
    // get the integer value from argument
    echo intval(true);      // 1
    echo intval(false);     // 0
    
    // simply echoing true returns 1
    echo true;              // 1
    
    // you can even add those values
    echo true + true;       // 2
    
    0 讨论(0)
提交回复
热议问题