


PHP comparison operations and logical operations, php operation logic_PHP tutorial
Jul 12, 2016 am 08:52 AMPHP 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:

<span>//</span><span>0開(kāi)頭的數(shù)字字符串轉(zhuǎn)數(shù)字時(shí)不會(huì)按八進(jìn)制轉(zhuǎn)換,而是簡(jiǎn)單地丟棄把 '0' 丟棄按數(shù)字進(jìn)行比較,</span> 123=='0123' <span>//</span><span>true</span> "123"<"0124" <span>//</span><span>true,0開(kāi)頭的數(shù)字字符串直接按十進(jìn)制數(shù)字比較而非八進(jìn)制</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 轉(zhuǎn) bool 是true</span>

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)

<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>

Several string to number conversion scenarios:

<span>echo</span> 'abc'*1 ; <span>//</span><span>0 </span> <span>echo</span> '012'*1; <span>//</span><span>12 乘法:可以轉(zhuǎn)換十六進(jìn)制數(shù),不是數(shù)字開(kāi)頭則返回 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 不能處理十六進(jìn)制數(shù)</span> <span>echo</span> (<span>float</span>)'12abc'; <span>//</span><span>12 截取左側(cè)字符串</span> <span>echo</span> (<span>float</span>)'abc'; <span>//</span><span> 0 不是數(shù)字返回0</span> <span>is_numeric</span>('0x123'); <span>//</span><span>true 能識(shí)別十六進(jìn)制數(shù)</span> <span>is_numeric</span>('0x123.123'); <span>//</span><span>false 識(shí)別目標(biāo)是整個(gè)字符串而非截取前面一部分</span>

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:

<span>//幾個(gè)轉(zhuǎn)字符串的值</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>

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)
來(lái)自類 b 的 private 屬性 f、k,(從數(shù)組 key 來(lái)看,以bf為例,無(wú)法判斷他是屬性名為bf,還是來(lái)自類b的私有屬性f)
來(lái)自類 A 的 private 屬性 k
無(wú)法鑒別 b 和 A 哪個(gè)是子類哪個(gè)是父類(僅從 array 的key來(lái)看,也無(wú)法推斷出原對(duì)象構(gòu)造自哪個(gè)類)
例子:

<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>

輸出結(jié)果:
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、 邏輯運(yùn)算總是返回 true 或 false (寫(xiě)多了 javascript 的人要注意),邏輯運(yùn)算符優(yōu)先級(jí)從高到低 為 &&、 ||、 and、 or ,邏輯運(yùn)算符的短路效果可以使用語(yǔ)句中,但記住他們不會(huì)像 javascript 中那樣返回一個(gè) 不是 boolean 類型的值,在表達(dá)式中使用要注意。

<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>

6、switch 的比較不是 "===" 而是 "==" (在 javascript 中是 "===")
7、 在 php4 中,object 之間的比較方式與 array 相同,在 php5 中 , object 類型間的 "==" 比較為 true的前 提是,他們屬于同一個(gè)類的實(shí)例(當(dāng)然還要進(jìn)行屬性的比較,這類似標(biāo)量的"==="比較),object 間的 "===" 比較為 true 的前提是他 們 就是同一個(gè)對(duì)象。
在 PHP4 中 ,不包括任何成員變量的對(duì)象 被 empty() 判斷為 true
字符串偏移 offset 取字符的 empty() 判定: 取對(duì)應(yīng) offset 的字符進(jìn)行判斷,在PHP5.4 以前,使用索引從字符串中取字符時(shí)會(huì)先將索引進(jìn)行取整,因此左側(cè)不包含數(shù)字的字符串都被轉(zhuǎn)換成0,PHP5.4之后,不再對(duì)非整形格式的字符串索引進(jìn)行取整,因此判斷為 true, 同理,isset() 判定為false. 如:

<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() 會(huì)忽略警告</span> <span>empty</span>(<span>$str</span>['a']); <span>//</span><span> false ,左側(cè)不包含數(shù)字字符串索引 PHP5.4之前被處理為 $str[0],PHP5.4之后,直接為判定 true </span>

無(wú)論是“不等于”還是”==“ ,不要在 PHP 的跨類型數(shù)據(jù)比較中使用”傳遞性“:
$a == $b; //true
$b == $c; //true
并不能說(shuō)明 $a == $c 為 true
數(shù)組的比較方法

<span>//</span><span> 數(shù)組是用標(biāo)準(zhǔn)比較運(yùn)算符這樣比較的</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> }

8、三元運(yùn)算符 ?: ,跟其他大多數(shù)編程語(yǔ)言不一樣,PHP 的三元運(yùn)算符是左結(jié)合的!

<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>

三元運(yùn)算表達(dá)式被劃分為
( <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' ;

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
