Home Backend Development PHP Tutorial Detailed explanation of php data type examples

Detailed explanation of php data type examples

Mar 15, 2018 pm 01:13 PM
php Example Detailed explanation

PHP supports 8 primitive data types. Four scalar types: boolean (Boolean), integer (integer), float (floating point type, also called double), string (string), two composite types: array (array), object (object), and finally There are two special types: resource (resource) and NULL (no type).

Note: If you want to check the value and type of an expression, use the var_dump() function. If you just want a human-readable representation of the type for debugging, use the gettype() function. To check a type, don't use gettype(), use the is_type function.

PHP is a weak language and will be automatically converted according to the program running environment. When using the == sign, if you compare a number and a string or compare a string involving numeric content, the string will be converted to Numerical values ​​and comparisons are performed numerically. This rule also applies to switch statements. (Please use === for absolute comparison)

To summarize, floating point type> integer type> string> Boolean type

  1. Boolean type

    When converted to boolean, the following values ​​are Considered FALSE:

    All other values ​​are considered TRUE (including any resources).

  • Boolean value FALSE itself

  • Integer value 0 (zero)

  • Floating point value 0.0 (zero)

  • The empty string, and the string "0"

  • An array containing no elements

  • Object that does not include any member variables (only applicable to PHP 4.0)

  • Special type NULL (including variables that have not been assigned a value)

  • SimpleXML object generated from empty tags

  • Integer type

    • Integer overflow: if A given number outside the range of integer will be interpreted as a float. Similarly, if the result of the operation exceeds the range of integer, float will be returned.

    • There is no integer division operator in PHP (unlike Java). 1/2 yields float0.5. The value can be cast to an integer, discarding the fractional part, or using the round() function for better rounding.

      <?php
      var_dump(25/7);         // float(3.5714285714286) 
      var_dump((int) (25/7)); // int(3)
      var_dump(round(25/7));  // float(4) 
      ?>
      Copy after login
    • When converting from a floating point number to an integer, it is rounded down.

    • Warning

      Never cast an unknown fraction to an integer, as this can sometimes lead to unpredictable results.

      <?php
      echo (int) ( (0.1+0.7) * 10 ); // 显示 7!
      ?>
      Copy after login
  • Float type

  • <?php
    $a = 0.1;
    $b = 0.9;
    $c = 1;
    var_dump(($a+$b)==$c);//true
    var_dump(($c-$b)==$a);//falseprintf("%.20f", $a+$b); // 1.00000000000000000000
    printf("%.20f", $c-$b); // 0.09999999999999997780?>
    Copy after login

    This problem occurs because floating point calculation involves precision. When floating point numbers are converted to binary May cause loss of accuracy.

  • So never believe that a floating point number is accurate to the last digit, and never compare two floating point numbers for equality.

  • If you really need higher precision, you should use arbitrary precision math functions.

  • 高精度运算的方法如下:
    bcadd 将两个高精度数字相加
    bccomp 比较两个高精度数字,返回-1,0,1
    bcp 将两个高精度数字相除
    bcmod 求高精度数字余数
    bcmul 将两个高精度数字相乘
    bcpow 求高精度数字乘方
    bcpowmod 求高精度数字乘方求模
    bcscale 配置默认小数点位数,相当于Linux bc中的”scale=”
    bcsqrt 求高精度数字平方根
    bcsub 将两个高精度数字相减
    Copy after login
  • As the above warning message states, due to internal expression reasons, there is a problem in comparing two floating point numbers for equality. However, there are roundabout ways to compare floating point values.

    To test floating-point numbers for equality, use a minimum error value that is only a tiny bit larger than that value. This value, also known as the machine epsilon or smallest unit integer, is the smallest difference value that can be accepted in the calculation.

    and are equal to five decimal places of precision.

    <?php
    $a = 1.23456789;
    $b = 1.23456780;
    $epsilon = 0.00001;
    if(abs($a-$b) < $epsilon) {
        echo "true";
    }
    ?>
    Copy after login
  • String type

  • If the string is enclosed in double quotes ("), PHP will parse some special characters: Such as \n, \\, \$

  • ##The most important feature of strings defined with double quotes is that the variables will be parsed. Strings are spliced ​​with '.' The type of values ​​associated with keys.

    You can use the array() language structure to create a new array. It accepts any number of comma-separated key => value pairs

  • array(  key =>  value , ...
             )
        // 键(key)可是是一个整数 integer 或字符串 string
        // 值(value)可以是任意类型的值
        此外 key 会有如下的强制转换:
            <?php
            $arr = array(5 => 1, 12 => 2);
            $arr[] = 56;    // This is the same as $arr[13] =56; at this point of the script
            $arr["x"] = 42; // This adds a new element to the array with key "x"                
            unset($arr[5]); // This removes the element fromthe array
            unset($arr);    // This deletes the whole array
    Copy after login

  • ## Strings containing legal integer values ​​will be converted to integers. For example, the key name "8" will actually be stored as 8, but "08" will not. It will be forced to convert because it is not a legal decimal value.
  • The floating point number will also be converted to an integer, which means that the decimal part will be rounded off. For example, the actual key name 8.7. will be stored as 8.

  • ##The Boolean value will also be converted into an integer. That is, the key name true will actually be stored as 1 and the key name false will be stored as 0.

  • # Null will be converted to an empty string, that is, the key name null will actually be stored as ""
    • Arrays and objects cannot be used. Key name. Insisting on this will result in the warning: Illegal offset type

    • If the same key name is used for multiple cells in the array definition, only the last one is used. are covered.

    • PHP arrays can contain both integer and string type key names, because PHP does not actually distinguish between index arrays and associative arrays

      .
    • 如果对给出的值没有指定键名,则取当前最大的整数索引值,而新的键名将是该值加一。

    • 如果指定的键名已经有了值,则该值会被覆盖。

    • 要删除某键值对,对其调用 unset() 函数。unset() 函数允许删除数组中的某个键。但要注意数组将不会重建索引。如果需要删除后重建索引,可以用 array_values() 函数。

  • foreach 控制结构是专门用于数组的。它提供了一个简单的方法来遍历数组。

  • 数组(Array) 的赋值总是会涉及到值的拷贝。使用引用运算符通过引用来拷贝数组。

  •  <?php
            $arr1 = array(2, 3);
            $arr2 = $arr1;
            $arr2[] = 4; // $arr2 is changed,// $arr1 is still array(2, 3)       
            $arr3 = &$arr1;
            $arr3[] = 4; // now $arr1 and $arr3 are the same
        ?>
    Copy after login
  • NULL
        特殊的 NULL 值表示一个变量没有值。NULL 类型唯一可能的值就是 NULL。
        在下列情况下一个变量被认为是 NULL:
            1. 被赋值为 NULL。2. 尚未被赋值。3. 被 unset()。
        转换到 NULL :使用 (unset) $var 将一个变量转换为 null 将不会删除该变量或 unset 其值。仅是返回 NULL 值而已。

  • 相关推荐:

    PHP数据类型转换的转换

    解析PHP数据类型之对象(Object)

    PHP数据类型之字符串类型

    PHP数据类型之布尔型变量详解

    php数据类型

    First operand type

    Second operand Type

    Type conversion

    Integer type

    Floating point type

    Convert integer type to floating point type

    ##Integer type

    String

    Convert the string to a number. If the string is converted to a floating point type, the integer type will also be converted to a floating point type

    Floating point type

    String

    Convert string to floating point type

    The above is the detailed content of Detailed explanation of php data type examples. For more information, please follow other related articles on the PHP Chinese website!

    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

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    Java Tutorial
    1653
    14
    PHP Tutorial
    1251
    29
    C# Tutorial
    1224
    24
    PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

    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

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    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,

    How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

    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

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    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.

    PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

    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

    PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

    PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

    What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

    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.

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    See all articles