[英]Handle a PHP error message when a second node doesn't exist?
希望有人可以幫忙
我正在使用它來獲取我的URL
的第一部分
$page_url = perch_page_url(['include-domain' => false,], true); //
Output the URL of the current page, minus https
$url_parts = explode("/", $page_url); // Split a string by a string
我正在使用這種技術來獲取URL
的第一個和第二個節點
$first_node = $url_parts[1]; // First part of string
$second_node = $url_parts[2]; // Second part of string
在我的主頁上,沒有第二個節點,因此收到undefined offset
消息。
有沒有辦法檢查$second_node
存在?
我試過使用
if (isset($second_node)) {
echo "$second_node is set so I will print.";
}
和
if (!empty($second_node)) {
echo '$second_node is either 0, empty, or not set at all';
}
兩個if
語句僅在設置$ second_node之后回顯? 所以我仍然收到錯誤消息。
請直接在if條件中使用它,避免分配給變量或在if條件中檢查后分配
if (isset($url_parts[2])) { // remove this line $second_node = $url_parts[2];
echo "$second_node is set so I will print.";
}
這是因為錯誤是在$second_node
變量的初始化時引發的。
首先檢查節點是否存在,然后聲明變量:
$second_node = ""; // Or whatever
if (isset($url_parts[2]) {
$second_node = $url_parts[2];
}
在這里檢查: https : //3v4l.org/fRJ7L
您可以執行以下操作:
$second_node = isset($url_parts[2]) ? $url_parts[2] : FALSE;
if ($second_node)
{
echo "Second node: {$second_node}";
}
這將檢查$url_parts
數組的第三個索引(從0開始)是否已設置。 如果是,它將其值分配給$second_node
。 如果沒有,它將分配為FALSE
因此如果您需要稍后(再次)進行檢查,則可以在代碼中進行進一步處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.