Last Updated: February 25, 2016
·
1.438K
· 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:

http://www.someWebSite.com/index.php/segment/segment2/segment3

echo giveMeSegment(2) returns /segment/segment2

OR

echo giveMeSegment(all) return the uri_string

OR

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){
    $ci=&get_instance();
    $string=0;

    if(is_numeric($until)){
        if($until==0){
            $string = base_url();
        }else{
            $string = '';
            for ($i=1; $i<=$until; $i++)
            {
                $string = $string.$ci->uri->segment($i).'/';
            }
        }
    }else{
        $string = $ci->uri->uri_string();
    }

    //if out of segments numbers
    return $string;
 }