How to force conversion into string in php
How to force conversion of php into a string: First create a PHP sample file; then define a variable; and finally force conversion into a string through the string method in PHP.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
PHP forced conversion type
Get the data type:
1. If you want to check the value and type of an expression, use var_dump().
2. If you just want to get an easy-to-read type expression for debugging, use gettype().
3. To view a certain type, do not use gettype(), but use the is_type() function.
■Convert string to numeric value
- When a string is evaluated as a number, the following rules are used Determine the type and value of the result.
- If it contains any of the characters ".", "e" or "E", the string is evaluated as a float. Otherwise it is treated as an integer.
- The value is determined by the first part of the string. If the string begins with legal numeric data, that number is used as its value, otherwise its value is 0 (zero). Legal numeric data begins with an optional sign, followed by one or more digits (optionally including a decimal fraction), followed by an optional exponent. The exponent is an "e" or "E" followed by one or more digits.
Note: Don't expect to get the encoding of a character when you convert it to an integer (you probably do this in C as well). If you wish to convert between character encodings and characters, use the ord() and chr() functions.
■Forced type casting
Type casting in PHP is very similar to that in C: in the variable to be converted Preceded by the target type enclosed in parentheses.
The allowed casts are:
- (int),(integer) - Convert to integer
- (bool),(boolean) - Convert to Boolean type
- (float),(double),(real) - Convert to floating point type
- (string) - Convert to string
- (array) - Convert to an array
- (object) - Convert to an object
Note that spaces and tabs are allowed within the brackets
You can also use settype (mixed var, string type) is forced to convert.
1. Forced conversion to Boolean value (bool)|(boolean)
To explicitly convert a value to boolean, use (bool ) or (boolean) to force conversion. But in many cases, casting is not necessary because when an operator, function, or flow control requires a boolean parameter, the value is automatically converted.
When converted to boolean, the following values are considered FALSE:
Boolean value FALSE
Integer value 0 (zero)
Floating point value 0.0 (zero)
Blank string and String "0"
Array with no member variables
Object without cells (only for PHP 4)
Special type NULL (including variables that have not been set)
All other values are considered is TRUE (including any resources).
<?php var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) ?>
2. Cast to integer (int)|(integer)
To explicitly convert a value to integer, use (int) or (integer) cast. In most cases, however, casting is not necessary because when an operator, function, or flow control requires an integer parameter, the value is automatically converted. You can also use the function intval() to convert a value to an integer type.
a. Convert from bool
b. Convert from floating point number, rounding, out of range, the result is uncertain
c. Convert from string, see Convert string to numeric value
d. Convert from other types first Change to a bool value and then convert
Never force an unknown fraction to an integer, as this can sometimes lead to unexpected results.
<?php echo (int) ( (0.1+0.7) * 10 ); // 显示 7 ?> $str = "123.456abc7"; // (int)123 echo (int)$str; $str = "abc123.456"; // (int)0 $str = true; // (int)1 $str = false; // (int)0
3.强制转换为浮点型 (int)|(double)|(real)|doubleval()|floatval()|intval()
精度: 0.12345678901234 // double,real都一样
数据的丢失参 字符串转换为数值
【推荐学习:《PHP视频教程》】
4.强制换为字符串 (string) |strval()
可以用 (string) 标记或者 strval() 函数将一个值转换为字符串。当某表达式需要字符串时,字符串的转换会在表达式范围内自动完成。例如当使用 echo() 或者 print() 函数时,或者将一个变量值与一个字符串进行比较的时候。
- 布尔值 TRUE 将被转换为字符串 "1",而值 FALSE 将被表示为 ""(即空字符串)。这样就可以随意地在布尔值和字符串之间进行比较。
- 整数或浮点数数值在转换成字符串时,字符串由表示这些数值的数字字符组成(浮点数还包含有指数部分)。
- 数组将被转换成字符串 "Array",因此无法通过 echo() 或者 print() 函数来输出数组的内容。请参考下文以获取更多提示。
- 对象将被转换成字符串 "Object"。如果因为调试需要,需要将对象的成员变量打印出来,请阅读下文。如果希望得到该对象所依附的类的名称,请使用函数 get_class()。自 PHP 5 起,如果合适可以用 __toString() 方法。
- 资源类型总是以 "Resource id #1" 的格式被转换成字符串,其中 1 是 PHP 在运行时给资源指定的唯一标识。如果希望获取资源的类型,请使用函数 get_resource_type()。
- NULL 将被转换成空字符串。
正如以上所示,将数组、对象或者资源打印出来,并不能提供任何关于这些值本身的有用的信息。请参阅函数 print_r() 和 var_dump(),对于调试来说,这些是更好的打印值的方法。
可以将 PHP 的值转换为字符串以永久地储存它们。这种方法被称为序列化,可以用函数 serialize() 来完成该操作。如果在安装 PHP 时建立了 WDDX 支持,还可以将 PHP 的值序列化为 XML 结构。
4. 强制转换为数组 (array)
- 对于任何的类型:整型、浮点、字符串、布尔和资源,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其下标为 0),该元素即为此标量的值。
- 如果将一个对象转换成一个数组,所得到的数组的元素为该对象的属性(成员变量),其键名为成员变量名。
- 如果将一个
<span style="font-family: NSimsun">NULL</span>
值转换成数组,将得到一个空数组。
5. 转换为对象 (object)
如果将一个对象转换成对象,它将不会有任何变化。如果其它任何类型的值被转换成对象,内置类 stdClass 的一个实例将被建立。如果该值为 NULL,则新的实例为空。数组转换成对象将使键名成为属性名并具有相对应的值。对于任何其它的值,名为 scalar 的成员变量将包含该值
6. 转换为资源 (无法转换)
由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄,因此无法将其它类型的值转换为资源。
■PHP 类型比较表
以下的表格显示了 PHP 类型和比较运算符在松散和严格比较时的作用。该补充材料还和类型戏法的相关章节内容有关。
- 注意
- HTML 表单并不传递整数、浮点数或者布尔值,它们只传递字符串。要想检测一个字符串是不是数字,可以使用 is_numeric() 函数。
- 在没有定义变量 $x 的时候,诸如 if ($x) 的用法会导致一个 E_NOTICE 级别的错误。所以,可以考虑用 empty
The above is the detailed content of How to force conversion into string in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
