溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

為什么PHP in_array(0,['a', 'b', 'c']) 返回為true

發(fā)布時(shí)間:2021-10-11 11:15:47 來(lái)源:億速云 閱讀:119 作者:柒染 欄目:大數(shù)據(jù)

本篇文章為大家展示了為什么PHP in_array(0,['a', 'b', 'c']) 返回為true,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

0、 問(wèn)題背景

在具體PHP編碼過(guò)程中,總會(huì)出現(xiàn)一些我們認(rèn)為不可能的情況,如下幾例:

in_array(0, ['a', 'b', 'c'])     // 返回bool(true),相當(dāng)于數(shù)組中有0
array_search(0, ['a', 'b', 'c']) // 返回int(0),相當(dāng)于是第一個(gè)值的下標(biāo)
0 == 'abc'                       // 返回bool(true),相當(dāng)于等值

但是,直觀上看, 0并沒(méi)有包含在['a', 'b', 'c']數(shù)組中,也不會(huì)等于'abc'這個(gè)字符串。那怎么解釋上述的返回結(jié)果呢?

1、 類型轉(zhuǎn)換

究其原因:在數(shù)據(jù)比較前,PHP做了類型轉(zhuǎn)換。引用PHP官網(wǎng)關(guān)于“String conversion to numbers”解釋如下:

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this
will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

文章開篇例子中,string類型數(shù)據(jù)第一個(gè)字符不是數(shù)字,就會(huì)轉(zhuǎn)換為0,例如:

echo intval('abc');  // 輸出0

inarray()和arraysearch()默認(rèn)都是松散比較,相當(dāng)于==,即得到true。

2、 嚴(yán)格比較

那怎么得到我們預(yù)期的結(jié)果呢?使用嚴(yán)格比較,如下所示:

in_array(0, ['a', 'b', 'c'], true)      // 返回bool(false)
array_search(0, ['a', 'b', 'c'], true)  // 返回bool(false)
0 === 'abc'                             // 返回bool(false)
3、 false 與 null

那么,如果用false和null與字符串?dāng)?shù)組比較,結(jié)果會(huì)如何呢?

in_array(null, ['a', 'b', 'c']) // 返回bool(false)
in_array(false, ['a', 'b', 'c']) // 返回bool(false)

null與false做比較值,字符串?dāng)?shù)組是不會(huì)轉(zhuǎn)換為int型的。

4、 數(shù)組中有true

另一個(gè)看起來(lái)比較奇怪的現(xiàn)象

in_array('a', [true, 'b', 'c'])     // 返回bool(true),相當(dāng)于數(shù)組里面有'a'
array_search('a', [true, 'b', 'c']) // 返回int(0),相當(dāng)于找到了字符串'a'

PHP語(yǔ)言本身是弱類型語(yǔ)言,為了便于應(yīng)用處理,會(huì)做一些類型轉(zhuǎn)換操作。

同時(shí)為了保證轉(zhuǎn)換精度準(zhǔn)確性等問(wèn)題,PHP官方建議:不要將未知的分?jǐn)?shù)強(qiáng)制轉(zhuǎn)換為 integer,這樣有時(shí)會(huì)導(dǎo)致不可預(yù)料的結(jié)果。

上述內(nèi)容就是為什么PHP in_array(0,['a', 'b', 'c']) 返回為true,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI