2016-11-07 132 views
1

所以我有這樣的代碼分配依賴於文件是否存在與否不同的變量:PHP - 擺脫if語句

$progress_file_path = './data/progress.txt'; 

if (file_exists($progress_file_path) && count($scanned) > 0) { 
    $scanned = file($progress_file_path); 
    $last = end($scanned); 
    $end = $limit + count($scanned); 
} 
else { 
    $last = 'unset'; 
    $end = $limit; 
} 

,但我需要做更多的這個問題,我需要確保該文件包含內容。我這樣做的條件是:

if (file_exists($progress_file_path) && count(file($scanned)) > 0) 

因爲$scanned變量尚未定義。所以理想的解決方案是如果我可以跳出if語句,並跳轉到條件的else部分。

事情是這樣的:

$progress_file_path = './data/progress.txt'; 

if (file_exists($progress_file_path)) { 
    $scanned = file($progress_file_path); 

    if (count($scanned) > 0) { break; } 

    $last = end($scanned); 
    $end = $limit + count($scanned); 

}I 
else { 
    $last = 'unset'; 
    $end = $limit; 
} 

但是,這並不工作,你不能突破或繼續出if語句的。我想可能使用goto跳轉到條件的else部分,但我懷疑這也可以。有沒有辦法跳到像這樣的條件的其他部分?

+0

'$ progress_file_path =」 ./data/ progress.txt「; 如果(file_exists($ progress_file_path)){$ 掃描=文件($ progress_file_path); if(count($ scanning)> 0){ \t \t $ last ='unset'; \t $ end = $ limit; }否則{ \t \t $最後=端($掃描); \t $ end = $ limit + count($ scanning); } }' –

+0

SelfDecode支持檢查答案並將其中一個標記爲接受的答案。如果將來有用,也可以對其他人進行投票。感謝 –

回答

1

煉油阿南特回答

$progress_file_path = './data/progress.txt'; 
$last = 'unset'; 
$end = $limit; 
if (file_exists($progress_file_path)) { 
    $scanned = file($progress_file_path); 
    if (count($scanned) < 0) { 
     $last = end($scanned); 
     $end = $limit + count($scanned); 
    } 
} 
1

你可以嘗試檢查您的兩個條件,一個if語句有至少一個其他人這樣

$progress_file_path = './data/progress.txt'; 

if (file_exists($progress_file_path) && count(file($progress_file_path)) > 0) { 
    $scanned = file($progress_file_path); 

    $last = end($scanned); 
    $end = $limit + count($scanned); 
} else { 
    $last = 'unset'; 
    $end = $limit; 
} 
+0

但是,如果文件$ progress_file_path(progress.txt)不存在,那麼當我嘗試使用文件打開文件時它會給出警告或錯誤( ) –

+0

這是正確的,但它不應該檢查它,如果該文件不存在。如果該文件不存在,則if的第一個條件爲false,並轉到else – DestinatioN