2011-06-04 127 views
2

我如何可以比較兩個變量的字符串,它會像這樣:比較變量PHP

$myVar = "hello"; 
if ($myVar == "hello") { 
//do code 
} 

,並檢查,看是否有$ _GET []變量是出現在URL會是這個樣子」

$myVars = $_GET['param']; 
if ($myVars == NULL) { 
//do code 
} 
+1

請告訴我你的問題?無論如何:第一個代碼片段完成一項任務,我想你想用「==」而不是「=」。如果查詢字符串中沒有「param」,第二個片段會給你一個警告(未定義索引)。 – cem 2011-06-04 22:30:42

回答

4
$myVar = "hello"; 
    if ($myVar == "hello") { 
    //do code 
    } 

$myVar = $_GET['param']; 
    if (isset($myVar)) { 
    //IF THE VARIABLE IS SET do code 
    } 


if (!isset($myVar)) { 
     //IF THE VARIABLE IS NOT SET do code 
} 

供您參考,東西跺着腳我好幾天,當第一次開始PHP:

$_GET["var1"] // these are set from the header location so www.site.com/?var1=something 
$_POST["var1"] //these are sent by forms from other pages to the php page 
+0

謝謝,我可以這樣做:$ myVar = $ _GET ['param'];如果(isset($ myVar)){} ... – Harigntka 2011-06-04 22:38:14

+0

是的,你確實可以,如果$ _get沒有值,它將不會被傳遞給myVar,因此它將被視爲NULL並且不會被預處理器設置。 – John 2011-06-04 22:42:14

+0

看到編輯,晚安和祝你好運 – John 2011-06-04 22:47:27

1

如果你想檢查如果變量設置,使用isset()

if (isset($_GET['param'])){ 
// your code 
} 
0

要將變量比較字符串,使用:

if ($myVar == 'hello') { 
    // do stuff 
} 

要看到,如果一個變量被設置使用isset()函數,就像這樣:

if (isset($_GET['param'])) { 
    // do stuff 
} 
0

所有這些信息都對PHP的網站上列出的下運營商

4

對於比較字符串,我建議在double equals上使用三等於運算符。

// This evaluates to true (this can be a surprise if you really want 0) 
if ("0" == false) { 
    // do stuff 
} 

// While this evaluates to false 
if ("0" === false) { 
    // do stuff 
} 

爲了檢查$ _GET變量我寧願使用array_key_exists,isset可以返回false如果該鍵存在,但內容爲空

類似:

$_GET['param'] = null; 

// This evaluates to false 
if (isset($_GET['param'])) { 
    // do stuff 
} 

// While this evaluates to true 
if (array_key_exits('param', $_GET)) { 
    // do stuff 
} 

如果可能避免做任務如:

$myVar = $_GET['param']; 

$ _GET,依賴於用戶。所以預期的鑰匙可能有或沒有。如果在訪問密鑰時該密鑰不可用,則會觸發運行時通知。如果啓用了通知,這可能會填充您的錯誤日誌,或在最糟糕的情況下將您的用戶發送給您。只要做一個簡單的array_key_exists來檢查$ _GET,然後再引用它上面的鍵。

if (array_key_exists('subject', $_GET) === true) { 
    $subject = $_GET['subject']; 
} else { 
    // now you can report that the variable was not found 
    echo 'Please select a subject!'; 
    // or simply set a default for it 
    $subject = 'unknown'; 
} 

來源:

http://ca.php.net/isset

http://ca.php.net/array_key_exists

http://php.net/manual/en/language.types.array.php