簡體   English   中英

PHP-打破if語句

[英]PHP - Break out of an if statement

所以我有這段代碼根據文件是否存在分配不同的變量:

$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部分,但是我懷疑這是否可行。 有沒有辦法跳到這樣的條件的其他部分?

您可以嘗試在一個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;
}

提煉Anant答案

$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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM