2011-04-28 93 views
0

嗨,大家好,我的if語句不起作用。我想基本上什麼都不做,數組是空的,或者如果它有值,就做些什麼。所有這一切發生的是「沒有選擇的額外」即使我選擇演員php空數組if語句

if (empty($extras)) { 
    $message .="<br /> No extras selected <br />"; 
    } else { 
    foreach($_POST['extras'] as $extra) 
    { 
     $message .="<br />Extras: ".$extra."<br />"; 

    } 
    } 
+0

是的,它是複選框的數組 – Simon 2011-04-28 12:51:23

回答

4

我假設這是一個錯字,作爲根據您的代碼$extras從未設置。

您應該使用

if (empty($_POST['extras'])) { 
0

我沒有測試過這顯示,但是你可以嘗試if(!isset($extras[0]))

+0

沒了,仍然dosent工作的幫助隊友 – Simon 2011-04-28 12:47:26

1

可能$extras變量是空的,但你通過$_POST['extras']迭代這是不一樣的。

+0

由於是存儲在$ _ POST – Simon 2011-04-28 13:00:52

0

什麼

if (empty($_POST['extras'])) { ... } 

您以前是否聲明過$extras變量?

+0

$演員 – Simon 2011-04-28 12:48:54

0
if(!empty($array)){ 
//do something 
}else{ 
//donothing 

} 

請試試這個,......

0

您可以用is_array()功能也試試。文檔here

0

如果您分配一個空數組到$extras變量在你的代碼(例如$extras = array(),那麼你基本上檢查$extras分配,而不是分配給它的數組的長度。

這應該爲你工作:

if(count($extras) == 0) { 
    // Your code here... 
} 
0

我覺得你的代碼應該是這樣的:

if (array_key_exists('extras', $_POST) and // check that the element exists in the $_POST array 
    !empty($_POST['extras'])) { // check that it is not empty 
    foreach ($_POST['extras'] as $extra) { 
     $message .="<br />Extras: " . $extra . "<br />"; 
    } 
} else { 
    $message .="<br /> No extras selected <br />"; 
} 

當前代碼中的邏輯是向後的。

+0

乾杯堆的幫助複選框數組 – Simon 2011-04-28 13:01:16