isset() vs empty()

So…

My plan was to create a home page with a PHP navigation include which would, playing to the link clicked, send a value to the URL address bar, change the formatting of the proper section title in the nav, and then pull in the page matching that specific value.
Here was my original code:


if ($section==NULL)
{
$section = "ads";
}
else
{
$section = $_GET['section'];
}

This worked if the user was clicking from within, but NOT when then user first came to the page. That produced an error of
Notice: Undefined variable: section in...on line 17
So… I tried isset.


if (isset($section))
{
$section = "ads";
}
else
{
$section = $_GET['section'];
}

That did not work either. If the user had not clicked anything yet, the variable was not set, and testing for it produced an error.

Notice: Undefined index: section in...on line 20
Warning: require(pages/.html) [function.require]: failed to open stream: No such file or directory in...on line 25
Fatal error: require() [function.require]: Failed opening required 'pages/.html' (include_path='.;c:\php\PEAR') in...on line 25

Then google showed me the way:

if (empty($_GET))
{
$section = "ads";
}
else
{
$section = $_GET['section'];
}

This worked perfectly. It tested whether the user had clicked and populated $_GET. If not, it would go ahead and set the variable.

CategoriesUncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *