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

is it necessary to assign value to null in function

function category_generate_Catalog($section,$limit = null, $offset = 0){
       include("connection.php");
       $section = strtolower($section);
       try{
       $sql = "Select media_id,title,category,img 
              FROM media
              WHERE LOWER(category) = ?
                ORDER BY REPLACE(
                    REPLACE(
                        REPLACE(title,'The ',''),
                        'An ',''
                    ),
                   'A ',''
                )";
        if(is_integer($limit)){
           $result = $db->prepare($sql."LIMIT ? OFFSET ?");  
           $result->bindParam(1,$section,PDO::PARAM_STR);
           $result->bindParam(2,$limit,PDO::PARAM_INT);
           $result->bindParam(3,$offset,PDO::PARAM_INT); 
        }else{
           $result = $db->prepare($sql);
           $result->bindParam(1,$section,PDO::PARAM_STR);
        }       
        $result->execute();

  }catch(Exception $e){
    echo "Unable to Retreived Result";
    echo $e->getMessage();
    exit;
  }
  $catalog = $result->fetchAll(PDO::FETCH_ASSOC);
  return $catalog;
}

1 Answer

Simon Woodard
Simon Woodard
6,545 Points

It is necessary to give all function arguments a default value (like $limit = null) if your not planning on assigning them every time you execute the function.

Assigning default values for your function arguments works well as a standard, and will allow for cleaner code within your project.

For instance: if you execute your function 50 times throughout your project, but only 10 of them require the $limit argument to be specifically supplied, then you won't have to manually supply a NULL value for the other 40.

eg.

// We don't need to supply the other two arguments if they are not necessary.
category_generate_Catalog('some section'); 

// If they don't have a default value, then we do need to supply them every time.
category_generate_Catalog('some section', NULL, 0);