Hope someone can help with this
I'm using this to grab the first part of my 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
$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.
Is there a way to check if the $second_node
exists?
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? 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 (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.
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
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. If yes, it will assign its value to $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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.