CodeIgniter - Get Last URI Segment
Asked Answered
P

5

19

I'm trying to get the last URI segment in CI, however I don't know what the number for it will be, as parameters (an integer) will be appended as the user clicks links within the page. These are then used in a controller to pull relevant database records into the page via ajax.

How can I tell CI to get the last segment?

Something like:

$record_num = $this->uri->segment($last);
Profess answered 30/9, 2010 at 10:41 Comment(1)
Thanks for the replies, both answers are good. I've gone Anpher's as it's a bit more concise.Profess
G
43
$record_num = end($this->uri->segment_array());
Gulp answered 30/9, 2010 at 11:16 Comment(3)
hi! i used this code but when the segment is not found then it's throw error please help. i write in if condition with empty but not work.Indisputable
always declare your parameter like public function name($parameter = " ")Picayune
Only variables should be passed by reference. Use Mischa answer instead.Replica
B
33

This should work:

$last = $this->uri->total_segments();
$record_num = $this->uri->segment($last);
Belligerency answered 30/9, 2010 at 11:8 Comment(2)
+1 I like this method better, since it uses codeigniter's functionality. It just seems like the right thing to do.Lowther
I agree, like this one better. You can save yourself a line too: $record_num = $this->uri->segment($this->uri->total_segments());Beshore
B
4

I needed this in 2021 and here's how I got to it

$record_num = end($this->uri->segments)

Ty to Anpher that got me in the right track

Blindheim answered 30/3, 2021 at 9:19 Comment(0)
F
0

Try this :

$last_segment = $this->uri->segment($this->uri->total_segments());
echo $last_segment;

Above code is for English language, for UTF8 such as Arabic, Persian, etc use :

$last_segment = $this->uri->segment($this->uri->total_segments());
echo urldecode($last_segment);
Finitude answered 24/4, 2022 at 17:10 Comment(0)
E
0

This worked for me with CodeIgniter 4.

// Instantiate CI request
$request = \Config\Services::request();

// Get full segment url after domain
$url = $request->getPath();

// search for slash in segment url
$pos = strrpos($url, '/');

// ternary if slash found return last segment including last slash
$last_seg = $pos === false ? $url : substr($url, $pos + 0);
Eximious answered 12/12, 2023 at 17:55 Comment(1)
It may works, but i'm sure there are more simple solutions.Growth

© 2022 - 2024 — McMap. All rights reserved.