1

I have the latest codeigniter version, and was wondering how can i get the segments in a url by their parameter name. For instance, here is a sample url:

www.somewebsitedomain.com/param1=something/param2=somethingelse/

now lets say i want to get the value for 'param1', which is 'something', how would i do so using the uri class?

Because by default the uri class only gets segments by number, or the order in which they appear, but i want to get segments by the parameter name in that segment. Or in general just get the parameter value. Hope that makes sense...

3 Answers 3

3

You could do $this->uri->uri_to_assoc(n) which will give something like the following

[array]
 (
'name' => 'joe'
'location'  => 'UK'
'gender'    => 'male'
)

Then just just the param name you would like.

Source: http://codeigniter.com/user_guide/libraries/uri.html

1
  • For the uri_to_assoc() method to work, the URI must be in the following format: domain.tld/key/value/key2/value2/key3/value3 etc.
    – Brendan
    Sep 25, 2012 at 5:26
1

You could actually put them as GET vars and use the Input Class:

$param = $this->input->get('param1'); // something

or you can do:

$params = $this->input->get(); // array('param1' => 'something', 'param2' => 'somethingelse')

to get all the parameters

0

I'm not sure this is what you're asking, but in many applications, URLs follow the form www.domain.com/controller/method/key1/value1/key2/value2. So I decided to extend the CI_URI class to return the value of any "key".

If you put this in your application/core folder, in a file named, MY_URI.php, it extends the built-in URI class:

class MY_URI extends CI_URI {

    /* call parent constructor */
    function __construct() {
        parent::__construct();
    }

    /* return value of the URI segment
       which immediately follows the named segment */
    function getNamed($str=NULL) {

        $key = array_search($str, $this->segments);

        if ($key && isset($this->segments[$key+1])) {
            return $this->segments[$key+1];
        }

        return false;

    }

}

Then if your URLs are in the form

www.somewebsitedomain.com/param1/something/param2/somethingelse/

you can call this function as follows:

$this->uri->getNamed('param1) - returns "something"

$this->uri->getNamed('param2) - returns "somethingelse"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.