FORM的欄位為空時,PHP的處理
背後核心的觀念:
(1) FORM在HTTP背後運作的原理
(2) 有出現在Request裡面的欄位,PHP才會幫它配置記憶體
1.情況一:text欄位為空
<form action='test2.php' method='POST'>
<input type='text' name='str' />
<input type='submit' />
</form>
如果str欄位什麼都不輸入就按下submit的話,HTTP在傳送POST Request時會有:
(其他變數)&str=&(其他變數)
PHP接收到(其他變數)&str=&(其他變數)以後,因為看到裡面有str=,所以會配置空間給$_POST['str']這個變數(有在Request裡面的欄位,PHP才會幫它配置記憶體)
由於等號後面並沒有東西,這相當於是"空字串",所以PHP會把$_POST['str']的值設定為""
也就是說PHP最後的處理是:$_POST['str'] = "";
2. 情況二:checkbox欄位為空
<form action='test2.php' method='POST'>
<input type='checkbox' name='str[A]' value='A' />
<input type='checkbox' name='str[B]' value='B' />
<input type='submit' />
</form>
如果str[A]項目有被勾選,但str[B]項目沒被勾選,那麼POST Request時會有:
(其他變數)&str[A]=A&(其他變數)
也就是說,沒被勾選的項目不會出現在Request裡面,既然沒出現在Request裡,PHP也不會為沒被勾選的項目配置記憶體。
換句話說,PHP不會配置變數$_POST['B']的記憶體。
2013年6月2日 星期日
isset(), empty() and is_null()
http://techtalk.virendrachandak.com/php-isset-vs-empty-vs-is_null/
大致上做個總結:
NULL是用來代表變數尚未被給值,或者變數還沒被配置記憶體
1. isset() - Determines if a variable is set(配置記憶體) and is not NULL
換句話說,只有變數是not null時isset()才會回傳true
2. empty() - Determines if a variable is empty
empty()在下面這些值時會回傳true:an empty string, false, array(), NULL, “0?, 0, and an unset variable
3. is_null() - Finds whether a variable is NULL
要注意,isset()可以被用在unknown variables上,但is_null只能被用在declared variables
題外話:unset()是用來把變數從記憶體中釋放
大致上做個總結:
NULL是用來代表變數尚未被給值,或者變數還沒被配置記憶體
1. isset() - Determines if a variable is set(配置記憶體) and is not NULL
換句話說,只有變數是not null時isset()才會回傳true
2. empty() - Determines if a variable is empty
empty()在下面這些值時會回傳true:an empty string, false, array(), NULL, “0?, 0, and an unset variable
3. is_null() - Finds whether a variable is NULL
要注意,isset()可以被用在unknown variables上,但is_null只能被用在declared variables
題外話:unset()是用來把變數從記憶體中釋放
訂閱:
意見 (Atom)