How to convert string to boolean type in php

青灯夜游
Release: 2023-03-11 07:08:02
Original
4315 people have browsed it

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);
?>
Copy after login

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);
?>
Copy after login

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);
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!