Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Integrating PHP with Databases Limiting Records in SQL Setting Up Pagination Variables

Dan Avramescu
Dan Avramescu
11,286 Points

Why isset and empty in 2 different statements?

Wouldn't be better if this code

if (isset($_GET['pg'])) {
    $current_page = filter_input(INPUT_GET,'pg',FILTER_SANITIZE_NUMBER_INT);
}
if (empty($_GET['pg'])) {
    $current_page = 1;
}

was written like

if (!empty($_GET['pg'])) {
    $current_page = filter_input(INPUT_GET,'pg',FILTER_SANITIZE_NUMBER_INT);
}else{
    $current_page = 1;
}

isset($_ GET['pg']) returns true even if the query wil be ?pg=0, while empty checks for 0, '0' ( the latter doesn't matter here since we use SANITIZE _ NUMBER _ INT). Ah, actually after reading the docs, i see the FILTER_SANITIZE_NUMBER_INT returns the number as a string :) Still, this question stands.

1 Answer

Hi Dan,

The second if condition was supposed to be if (empty($current_page)) {

The idea here is that you first check if it's set and sanitize it by removing non-numeric characters.

The second if is to make sure you didn't get back an empty string or "0".

With your rewritten code, it's not going to work when the 'pg' variable is non-numeric. Example: ?pg=abc

Your if condition will be true because it's not empty and then $current_page will be set to an empty string once the letters are stripped out of it.