In Documentation (https://www.codeigniter.com/user_guide/incoming/routing.html#id39): Offsetting the Matched Parameters
You can offset the matched parameters in your route by any numeric value with the offset option, with the value being the number of segments to offset.
This can be beneficial when developing APIs with the first URI segment being the version number. It can also be used when the first parameter is a language string:
<?php
$routes->get('users/(:num)', 'users/show/$1', ['offset' => 1]);
// Creates:
$routes['users/(:num)'] = 'users/show/$2';
I read this and I don't know how to use it. Can I have a usage example from route to controller?
This is that code that implements offset:
if (isset($options['offset']) && is_string($to)) {
// Get a constant string to work with.
$to = preg_replace('/(\$\d+)/', '$X', $to);
for ($i = (int) $options['offset'] + 1; $i < (int) $options['offset'] + 7; $i++) {
$to = preg_replace_callback(
'/\$X/',
static fn ($m) => '$' . $i,
$to,
1
);
}
}
As i understand it, it increments the $1,$2
... by offset
. So if we take the example code it turns $1
to $2
.
This means the first matched parameter (v1
) of an url example.com/users/v1/2
, that is matched by the route definition ($routes->get('users/(:num)', 'users/show/$1', ['offset' => 1]);
), is omitted and the second one (2
) gets passed to the controller function.