search
HomeBackend DevelopmentPHP TutorialPHP comparison operations and logical operations, php operation logic_PHP tutorial

PHP comparison operations and logical operations, PHP operation logic

1. The following values ​​are judged to be true using empty():

UnassignedVariable, undeclared variable, 0, "0", "", false, null, empty array array(), object's magic method __get() Returned value

In versions lower than PHP5.0, objects without any attributes are also judged as empty by empty

Note: empty() only accepts variables or index values ​​or attribute values ​​of variables. Constants cannot be passed in directly, nor operation expressions can be passed in. Expressions are supported after PHP 5.5

2. Values ​​judged as false by isset(): unassigned variables, undeclared variables, null, values ​​returned by __get() accept the same participation as empty(), and cannot be constants and expressions.

3. Comparison of different types of data

If one of them is of boolean type or null, convert it to boolean for comparison,

Otherwise, if one is a number, convert it to number and compare ,

Otherwise, if one of them is a string, convert it to string and compare

Object type is always greater than array type and scalar type, array type is always greater than scalar type

Note these comparison results:

PHP comparison operations and logical operations, php operation logic_PHP tutorial
       <span>//</span><span>0开头的数字字符串转数字时不会按八进制转换,而是简单地丢弃把 '0' 丢弃按数字进行比较,</span>

      123=='0123' <span>//</span><span>true</span>
      "123"<"0124" <span>//</span><span>true,0开头的数字字符串直接按十进制数字比较而非八进制</span>

      "012" == 10 <span>//</span><span> false</span>
       012 == 10  <span>//</span><span> true</span>
       0x12 == 18  <span>//</span><span> true</span>
       "0x12" == 18 <span>//</span><span> true</span>
 

 <span>false</span> < <span>true</span>; <span>//</span><span>true</span>
 2><span>true</span>; <span>//</span><span> false</span>
 2==<span>true</span>; <span>//</span><span> true </span>
 <span>null</span>==0; <span>//</span><span>true</span>
-1<0;<span>//</span><span>true</span>
-1<<span>null</span>;<span>//</span><span>false ,-1 转 bool 是true</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

4. Type conversion rules

The value judged as true by empty() is converted to boolean type to get false , otherwise, it is true (the value returned by __get() needs to be a specific value Judgment)

The value judged as true by empty() is converted to number and the result is 0. The non-empty array is converted to number and the value is 1 (the value returned by __get() needs to be judged according to the specific value)

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>class</span><span> Test{
   </span><span>private</span> <span>$k</span>=1<span>;
   </span><span>public</span> <span>function</span> __get(<span>$propertyName</span><span>){
       </span><span>return</span> 123<span>;
   }
}

</span><span>$obj</span> = <span>new</span><span> Test();
</span><span>echo</span> json_encode(<span>empty</span>(<span>$obj</span>->k)); <span>//</span><span>true</span>
<span>echo</span> json_encode(<span>isset</span>(<span>$obj</span>->k)); <span>//</span><span>false</span>
<span>echo</span> json_encode((bool)(<span>$obj</span>->k)); <span>//</span><span>true</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

Several string to number conversion scenarios:

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>echo</span> 'abc'*1 ; <span>//</span><span>0 </span>
<span>echo</span> '012'*1; <span>//</span><span>12  乘法:可以转换十六进制数,不是数字开头则返回 0</span>
<span>echo</span> '0x12.123'*1; <span>//</span><span>18</span>

<span>echo</span> (<span>float</span>)'0x12' ;<span>//</span><span>0 </span>
<span>echo</span> (int)'0x12' ; <span>//</span><span>0 不能处理十六进制数</span>
<span>echo</span> (<span>float</span>)'12abc'; <span>//</span><span>12 截取左侧字符串</span>
<span>echo</span> (<span>float</span>)'abc'; <span>//</span><span> 0 不是数字返回0</span>

<span>is_numeric</span>('0x123'); <span>//</span><span>true 能识别十六进制数</span>
<span>is_numeric</span>('0x123.123'); <span>//</span><span>false 识别目标是整个字符串而非截取前面一部分</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

When converting string to number, intercept the numeric string on the left for conversion. If there is no string, return 0.

Convert other data to string:

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>//几个转字符串的值</span>
(<span>string</span>)0 ; <span>//</span><span> "0"</span>
(<span>string</span>)<span>true</span>; <span>//</span><span> "1"</span>
(<span>string</span>)<span>false</span>; <span>//</span><span> ""</span>
(<span>string</span>)<span>null</span>; <span>//</span><span> ""</span>
(<span>string</span>)<span>array</span>(); <span>//</span><span> "<span>Array</span>"</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

Arrays can be directly concatenated with strings but cannot be subjected to mathematical operations.

Converting the object type to boolean is always true. The object type cannot be converted to number and string, so string splicing and mathematical operations cannot be performed

The way to convert a scalar into an array is to set the first element of the array to a scalar and return the array.

The scalar is converted to object to get an instance of the stdClass class. The value of the scalar is assigned to the attribute named scalar: Object( [scalar] => 234)

Convert array to object to get an instance of stdClass class. The key of the array is the property name of the class.

Object to array conversion is a bit complicated:

Methods, static properties, and class constants are discarded

The protected attribute name is preceded by a "*"

Private attributes are prefixed with the class name (the case is exactly the same as the class name)

 Add space characters before and after these prefixes For example, an array converted from object is:

<span>Array</span>(    [*v] => 444    [bf] => 333    [bk] => 99977    [Ak] => 999    [*p] => 888    [a2] => 22)

The original objects include:

Public attribute a2, protected attribute v, p, which class these attributes come from cannot be identified (if overridden, the attributes of the subclass will be taken)

          来自类 b 的 private 属性 f、k,(从数组 key 来看,以bf为例,无法判断他是属性名为bf,还是来自类b的私有属性f)

          来自类 A 的 private 属性 k 

          无法鉴别 b 和 A 哪个是子类哪个是父类(仅从 array 的key来看,也无法推断出原对象构造自哪个类)

 

例子:

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>class</span><span> A {
    </span><span>private</span> <span>$A</span> = 'private property, $A of class A'; <span>//</span><span> This will become '\0A\0A'</span>
    <span>protected</span> <span>$C</span> = 'protected property, $C of class A'<span>;
}

</span><span>class</span> B <span>extends</span><span> A {
    </span><span>private</span> <span>$A</span> = 'private property, $A of class B'; <span>//</span><span> This will become '\0B\0A'</span>
    <span>public</span> <span>$AA</span> = 'public property, $AA of class B'; <span>//</span><span> This will become 'AA'</span>
    <span>protected</span> <span>$B</span> = 'protected property, $B of class B'<span>;
}

</span><span>$arr</span> = (<span>array</span>) <span>new</span><span> B();

</span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$key</span> => <span>$value</span><span>) {
    </span><span>echo</span> '<br />'<span>;
    </span><span>echo</span> <span>$key</span> .',length: '.<span>strlen</span>(<span>$key</span>).' value: '.<span>$value</span><span>;
}</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

 

输出结果:

BA,length: 4 value: <span>private</span> property, <span>$A</span> of <span>class</span><span> B
AA</span>,length: 2 value: <span>public</span> property, <span>$AA</span> of <span>class</span><span> B
</span>*B,length: 4 value: <span>protected</span> property, <span>$B</span> of <span>class</span><span> B
AA</span>,length: 4 value: <span>private</span> property, <span>$A</span> of <span>class</span><span> A
</span>*C,length: 4 value: <span>protected</span> property, <span>$C</span> of <span>class</span> A

 

 

5、 逻辑运算总是返回 true 或 false (写多了 javascript 的人要注意),逻辑运算符优先级从高到低 为 &&、 ||、 and、 or ,逻辑运算符的短路效果可以使用语句中,但记住他们不会像 javascript 中那样返回一个 不是 boolean 类型的值,在表达式中使用要注意。

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>$a</span> = 1<span>;
</span><span>$b</span>=0<span>;
</span><span>$b</span> and <span>$a</span> = 100<span>;
</span><span>echo</span> <span>$a</span>; <span>//</span><span>1</span>
<span>$b</span> || <span>$a</span> = 200<span>;
</span><span>echo</span> <span>$a</span>; <span>//</span><span>200</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

 

 

 

6、switch 的比较不是 "===" 而是 "==" (在 javascript 中是 "===")

 

7、 在 php4 中,object 之间的比较方式与 array 相同,在 php5 中 , object 类型间的 "==" 比较为 true的前 提是,他们属于同一个类的实例(当然还要进行属性的比较,这类似标量的"==="比较),object 间的 "===" 比较为 true 的前提是他 们 就是同一个对象。

 

在 PHP4 中 ,不包括任何成员变量的对象 被 empty() 判断为 true

字符串偏移 offset 取字符的 empty() 判定: 取对应 offset 的字符进行判断,在PHP5.4 以前,使用索引从字符串中取字符时会先将索引进行取整,因此左侧不包含数字的字符串都被转换成0,PHP5.4之后,不再对非整形格式的字符串索引进行取整,因此判断为 true, 同理,isset() 判定为false. 如:

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>$str</span> = 'ab0d'<span>;
</span><span>empty</span>(<span>$str</span>[0]); <span>//</span><span>false</span>
<span>empty</span>(<span>$str</span>[0.5]); <span>//</span><span>false  索引被向下取整 为 0</span>
<span>empty</span>(<span>$str</span>["0.5"]); <span>//</span><span>false 索引被向下取整 为 0,PHP5.4之后不取证,判定为 true </span>
<span>empty</span>(<span>$str</span>[2]); <span>//</span><span>true ,取得的字符为 "0"</span>
<span>empty</span>(<span>$str</span>["3"]); <span>//</span><span>false ,取得的字符为 "d"</span>
<span>empty</span>(<span>$str</span>[4]); <span>//</span><span>true ,索引超出范围,notice 警告,但 empty() 会忽略警告</span>
<span>empty</span>(<span>$str</span>['a']); <span>//</span><span> false ,左侧不包含数字字符串索引 PHP5.4之前被处理为 $str[0],PHP5.4之后,直接为判定 true </span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial

 

无论是“不等于”还是”==“ ,不要在 PHP 的跨类型数据比较中使用”传递性“:

$a == $b; //true

$b == $c; //true

并不能说明 $a == $c 为 true

 

数组的比较方法

PHP comparison operations and logical operations, php operation logic_PHP tutorial
<span>//</span><span> 数组是用标准比较运算符这样比较的</span>
<span>function</span> standard_array_compare(<span>$op1</span>, <span>$op2</span><span>)
{
    </span><span>if</span> (<span>count</span>(<span>$op1</span>) < <span>count</span>(<span>$op2</span><span>)) {
        </span><span>return</span> -1; <span>//</span><span> $op1 < $op2</span>
    } <span>elseif</span> (<span>count</span>(<span>$op1</span>) > <span>count</span>(<span>$op2</span><span>)) {
        </span><span>return</span> 1; <span>//</span><span> $op1 > $op2</span>
<span>    }
    </span><span>foreach</span> (<span>$op1</span> <span>as</span> <span>$key</span> => <span>$val</span><span>) {
        </span><span>if</span> (!<span>array_key_exists</span>(<span>$key</span>, <span>$op2</span><span>)) {
            </span><span>return</span> <span>null</span>; <span>//</span><span> uncomparable</span>
        } <span>elseif</span> (<span>$val</span> < <span>$op2</span>[<span>$key</span><span>]) {
            </span><span>return</span> -1<span>;
        } </span><span>elseif</span> (<span>$val</span> > <span>$op2</span>[<span>$key</span><span>]) {
            </span><span>return</span> 1<span>;
        }
    }
    </span><span>return</span> 0; <span>//</span><span> $op1 == $op2</span>
}
PHP comparison operations and logical operations, php operation logic_PHP tutorial

 

 

 

8、三元运算符 ?: ,跟其他大多数编程语言不一样,PHP 的三元运算符是左结合的!

PHP comparison operations and logical operations, php operation logic_PHP tutorial
    <span>$arg</span> = 'T'<span>;    
    </span><span>$vehicle</span> = ( ( <span>$arg</span> == 'B' ) ? 'bus' :<span>    
                 ( </span><span>$arg</span> == 'A' ) ? 'airplane' :<span>   
                 ( </span><span>$arg</span> == 'T' ) ? 'train' :<span>    
                 ( </span><span>$arg</span> == 'C' ) ? 'car' :<span>    
                 ( </span><span>$arg</span> == 'H' ) ? 'horse' :    
                 'feet'<span> );    
    </span><span>echo</span> <span>$vehicle</span>;   <span>//</span><span>horse</span>
PHP comparison operations and logical operations, php operation logic_PHP tutorial


 

三元运算表达式被划分为

( <span>$arg</span> == 'B' ) ? 'bus' : ( <span>$arg</span> == 'A'<span> ) 
                                    </span>? 'airplane' : ( <span>$arg</span> == 'T'<span> ) 
                                                             </span>? 'train' : ( <span>$arg</span> == 'C'<span> )
                                                                               </span>? 'car' : ( <span>$arg</span> == 'H'<span> )
                                                                                                    </span>? 'horse' : 'feet' ;   

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1125682.htmlTechArticlePHP comparison operations and logical operations, php operation logic 1. The following values ​​are judged to be true using empty(): Unassigned variables, undeclared variables, 0, "0", "", false, null, empty array array()...
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools