程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP STRING 陷阱原理說明

PHP STRING 陷阱原理說明

編輯:關於PHP編程

A string is series of characters.
String access and modification by character
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.
Note: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 5.3.0. Use square brackets instead, such as $str[42].
Warning
Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_NOTICE. Negative offset emits E_NOTICE in write but reads empty string. Only the first character of an assigned string is used. Assigning empty string assigns NUL byte.

以上都是 php manual 中的原話。
需要注意的時候,我們訪問數組的時候 都是使用方括號“[]”,string作為一個也可以使用操作符“[]”進行訪問。但是,需要注意的一點就是,訪問字符串時候,操作符“[]”中的內容會被轉化為int類型的。
eg: $str ='123456';
echo $str['php'];//結果是1,因為offset ‘php'轉化為integer為0,既是訪問的是字符串的第一個字符.
var_dump(isset($str['php']));//結果是bool(true) 原理同上。
所以,在我們使用isset判斷一個設置是否存在某個鍵時候,應該先判斷試下,傳遞過來的變量是否是數組,然後再判斷是否是存在指定的key
eg://如果需要判斷傳遞過來的數組是否存在'php'這個key時候,比較安全的做法為:
復制代碼 代碼如下:
function is_set($arr, $key){
if (is_array($arr) && isset($arr[$key])) {
//存在該值的邏輯
} else{
//$arr不是數組 或者 數組$arr不存在key $key的邏輯
}
}

如果 上面的函數 沒有添加 is_array 的判斷,當傳遞一個 字符串過來的時候, 結果就不是我們預想的那樣了。

僅此為記,以免以後也出現類似的問題。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved