how to set optional third parameter in routes of codeigniter
Certainly! To set an optional third parameter in routes using CodeIgniter, follow these steps:
Open the
application/config/routes.php
file in your CodeIgniter project.Define your route with placeholders for the parameters you want. For example:
php $route['products/(:any)/(:any)/(:any)'] = 'catalog/product_lookup/$1/$2/$3';
The placeholders
(:any)
represent segments in the URL. In this case, the third parameter is optional due to its placement and lack of constraints.The route maps to the
catalog
controller'sproduct_lookup
method. The parameters captured in the URL segments are passed as arguments to this method.If the URL contains three segments after
/products/
, all three will be passed as arguments. If there are only two segments, the third parameter will be considered optional and can be handled accordingly in your controller method:
php
public function product_lookup($param1, $param2, $param3 = null) {
// $param1, $param2 will always have values
// $param3 will be null if not provided in the URL
// Your code logic here
}
- The
$param3
variable in theproduct_lookup
method will be set tonull
if the third parameter is not present in the URL. You can check for its presence and handle it accordingly within your controller method.