Welcome Guest, Not a member yet? Register   Sign In
Function that checks if a segment key exists ?
#1

[eluser]starbbs[/eluser]
Call me stupid but i need a function that simply returns the key if this key exists inside the URI class. I cannot seem to fin it. Let me explain:

Code:
/**
*   This returns true, even is the segment does NOT exist. Example:
*
*    $segment = array( 1 => 'cpanel',
*                      2 => 'admin',
*                      3 => 'module',
*                      4 => 'user',
*                      5 => '44');
*/

  // In my code, i use this to get the value:
  $segVal = $this->uri->segment(6, 0);

  // If all goes well, $segVal contains FALSE. but when i do:
  $segVal = (is_numeric($this->uri->segment(6, 0)) ? TRUE : FALSE;

  // Now segVal contains TRUE !

So, i was thinking that there might be a function, in where i can check for a key directly. But i cannot find this function. I created my own function. Maybe someone can think of a faster way:

Code:
// $name = the name of the segment you want to check
    // $return_index = When set to true, it returns the index of $name
    //                 When set to false, it returns $name when found
    // result: when found, the name or it's key, when nothing is found, it returns false
    
    function nsegment($name, $return_index = FALSE )
    {          
       if( in_array( $name, array_values($this->router->segments)))
       {
            foreach($this->router->segments as $segmentidx => $value ) {
                if($name == $value) {
                 if($return_index){
                  return $segmentidx;
                  }else return $value;
                }
            }
       }else
         return FALSE;
    }
     /* $cpanelidx contains '3' */
    $cpanelidx = $this->CI->uri->segmentn('module', TRUE);  
  
    /* $cpanel contains 'module' */
    $cpanel = $this->uri->nsegment('module');

If you have any suggestion for my problem, please reply!

Thnks @
#2

[eluser]xwero[/eluser]
You use the second argument of the segment method, this means if the 6th segment is not found 0 will be returned so your is_numeric check will always be true.
#3

[eluser]starbbs[/eluser]
Good one...




Theme © iAndrew 2016 - Forum software by © MyBB