2012-08-01 91 views
0

如何縮短代碼?例如用foreach。使重複代碼更短

if($Email == NULL){ 
     $Email = "-"; 
    } 
    elseif($Age == NULL){ 
     $Age = "-"; 
    } 
    elseif($Sex == NULL){ 
     $Sex = "-"; 
    } 

它必須被替換這樣

$search = array("%UserID%", "%RegDate%", "%Name%", "%Email%", "%Age%", "%Gender%"); 
$replace = array($UserID, $RegDate, $Name, $Email, $Age, $Sex); 
$content = str_replace($search, $replace, $content); 

編輯:

我知道了現在這個樣子是有可能使用變量$ = $行三元代碼呢?順便說一句我有一個variables.php文件,我使用三元代碼來定義,我已經嘗試過那裏,但因爲它早些時候使用它沒有工作,我沒有想到它:P

但是,這當前的代碼工作我只是想知道它是否可以縮短。

while($row = mssql_fetch_assoc($accountinforesult)){ 
    $UserID = $row['UserID']; 
    $RegDate = $row['RegDate']; 
    $Name = $row['Name']; 
    $Email = $row['Email']; 
    $Age = $row['Age']; 
    $Sex = $row['Sex']; 

    $UserID = isset($UserID) ? $UserID : "-"; 
    $RegDate = isset($RegDate) ? $RegDate : "-"; 
    $Name = isset($Name) ? $Name : "-"; 
    $Email = isset($Email) ? $Email : "-"; 
    $Age = isset($Age) ? $Age : "-"; 
    $Sex = isset($Sex) ? $Sex : "-"; 
} 

回答

1

未測試,但我相信這應該工作。

$vars = array('UserID', 'RegDate', 'Name', 'Email', 'Age', 'Sex'); 
foreach ($vars as $k => $v) { 
    $$v = ($$v !== NULL) ? $$v : '-'; 
} 

$$ v表示「名稱爲$ v的變量」。如果$ v ='foo',那麼$$ v是$ foo。

看「變量變量」:http://php.net/manual/en/language.variables.variable.php

+0

這一個工程太謝謝你那真的有用,看起來不錯! – 2012-08-01 17:53:04

+1

極好的解決方案,佩德羅!沒有人會想到。 – Matt 2012-08-01 17:57:34

+1

恕我直言,這是我強烈建議避免的解決方案!動態變量對於任何問題都是非常糟糕的解決方案。 – fdomig 2012-08-01 18:11:59

0
$Email = is_null($Email) ? "-" : $Email; 

算起來其餘

0

我知道了現在這個樣子是有可能使用變量$ = $行的三元代碼太? 順便說一句我有,我用三元代碼來定義一個variables.php文件,我已經嘗試過那裏,但因爲它被更早使用它沒有工作,我沒想到的是:P

但這當前代碼工作我只是想知道它是否可以縮短。

while($row = mssql_fetch_assoc($accountinforesult)){ 
    $UserID = $row['UserID']; 
    $RegDate = $row['RegDate']; 
    $Name = $row['Name']; 
    $Email = $row['Email']; 
    $Age = $row['Age']; 
    $Sex = $row['Sex']; 

    $UserID = isset($UserID) ? $UserID : "-"; 
    $RegDate = isset($RegDate) ? $RegDate : "-"; 
    $Name = isset($Name) ? $Name : "-"; 
    $Email = isset($Email) ? $Email : "-"; 
    $Age = isset($Age) ? $Age : "-"; 
    $Sex = isset($Sex) ? $Sex : "-"; 
} 
0
$params = array(
    'Email' => $Email, 
    'Age' => $Age, 
    'Gender' => $Sex, 
); 

foreach($params as $paramName => $paramValue) { 
    $paramValue = is_null($paramValue) ? '-' : $paramValue; 
    //$paramValue = mysql_real_escape_string($paramValue); // or something like that... 
    $content = str_replace('%'.$paramName.'%', $paramValue, $content); 
}