简体   繁体   English

当第二个节点不存在时,处理PHP错误消息?

[英]Handle a PHP error message when a second node doesn't exist?

Hope someone can help with this 希望有人可以帮忙

I'm using this to grab the first part of my URL 我正在使用它来获取我的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

I'm using this technique to grab the first and second nodes of the URL 我正在使用这种技术来获取URL的第一个和第二个节点

$first_node = $url_parts[1]; // First part of string 
$second_node = $url_parts[2]; // Second part of string

On my homepage, there isn't a second node, so I get an undefined offset message. 在我的主页上,没有第二个节点,因此收到undefined offset消息。

Is there a way to check if the $second_node exists? 有没有办法检查$second_node存在?

I've tried using 我试过使用

if (isset($second_node)) {
echo "$second_node is set so I will print.";
}

and

if (!empty($second_node)) {
echo '$second_node is either 0, empty, or not set at all';  
}

Both if statements only echo after the $second_node has been set? 两个if语句仅在设置$ second_node之后回显? So I still get the error message. 所以我仍然收到错误消息。

Please use it directly in the if condition and avoid assigning to a variable or assign after checking it in if condition 请直接在if条件中使用它,避免分配给变量或在if条件中检查后分配

if (isset($url_parts[2])) { // remove this line $second_node = $url_parts[2]; 
echo "$second_node is set so I will print.";
}

That is because the error is thrown at the initialization of your $second_node variable. 这是因为错误是在$second_node变量的初始化时引发的。

Check if the node exists first, and then declare the variable: 首先检查节点是否存在,然后声明变量:

$second_node = ""; // Or whatever
if (isset($url_parts[2]) {
    $second_node = $url_parts[2];
}

Check it here: https://3v4l.org/fRJ7L 在这里检查: https : //3v4l.org/fRJ7L

You can do something like this: 您可以执行以下操作:

$second_node = isset($url_parts[2]) ? $url_parts[2] : FALSE;
if ($second_node)
{
    echo "Second node: {$second_node}";
}

This checks if the third index (0-based) of the $url_parts array is set. 这将检查$url_parts数组的第三个索引(从0开始)是否已设置。 If yes, it will assign its value to $second_node . 如果是,它将其值分配给$second_node If not, it will assign FALSE so you can handle that further down in the code if you need to check it later (again). 如果没有,它将分配为FALSE因此如果您需要稍后(再次)进行检查,则可以在代码中进行进一步处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM