Home  >  Article  >  Backend Development  >  How to convert string to boolean type in php

How to convert string to boolean type in php

青灯夜游
青灯夜游Original
2021-07-01 18:36:264340browse

Conversion method: 1. Add the target type "(bool)" or "(boolean)" enclosed in parentheses before the conversion variable; 2. Use the boolval() function, the syntax "boolval(string) )"; 3. Use the settype() function with the syntax "settype(variable, "boolean")".

How to convert string to boolean type in php

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

php will string Method of converting to Boolean type

Method 1: Add the target type "(bool)" or "(boolean)" enclosed in parentheses before the conversion variable

<?php
    header("Content-type:text/html;charset=utf-8");
    $str = "123abc";
    echo &#39;变量的原类型为:&#39;;
	var_dump($str);
    $bool = (bool)$str;
    echo &#39;变量转换后的类型为:&#39;;
	var_dump($bool);
?>

Output:

How to convert string to boolean type in php

Method 2: Use boolval() function

boolval(): Use Used to get the Boolean value of the variable;

<?php
    header("Content-type:text/html;charset=utf-8");
    $str = "hello";
    echo &#39;变量的原类型为:&#39;;
	var_dump($str);
    $bool = boolval($str);
    echo &#39;变量转换后的类型为:&#39;;
	var_dump($bool);
?>

Output:

How to convert string to boolean type in php

Method 3: Use the bsettype() function

settype(): used to set the type of a variable; the settype() function changes the type of the variable itself.

Return value: TRUE when the setting is successful, FALSE when the setting fails.

Example:

<?php
    header("Content-type:text/html;charset=utf-8");
    $str = "hello";
    echo &#39;变量的原类型为:&#39;;
    var_dump($str);
    $bool = settype($str,"boolean");
    echo &#39;变量转换后的类型为:&#39;;
    var_dump($str);
?>

Output:

How to convert string to boolean type in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert string to boolean type in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use php $_filesNext article:How to use php $_files