Last Updated: February 25, 2016
· emanuelcoelho1986

Codeigniter automatic segments

The objective of this function id to return a uri segment in the range of the segment number user wants. It can be very useful for breadcrums anchors.
Returns the wanted segment or 0 if doesn't exist.

For example:

echo giveMeSegment(2) returns /segment/segment2


echo giveMeSegment(all) return the uri_string


echo giveMeSegment(0) returns the base_url

You just need to create a givemesegment_helper.php and place the function inside the <?php ?> tags and the file inside /application/helpers/. Then you can autoload it or just load it where you need it.

I hope it helps.

function giveMeSegment($until){

            $string = base_url();
            $string = '';
            for ($i=1; $i<=$until; $i++)
                $string = $string.$ci->uri->segment($i).'/';
        $string = $ci->uri->uri_string();

    //if out of segments numbers
    return $string;