DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Function Which Helps To Avoid Using Empty/isset

01.19.2010
| 5934 views |
  • submit to reddit
        Hey..

here is a function which helps to avoid using empty/isset
checkings for arrays.

(it's acts simillar to 'default' modifier in Smarty)

Using this function you will avoid 'Undefined index' or
'Undefined offset' error.
// 

<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
    preg_match_all('!(\w+)!i',$var, $match );
    array_shift($match);
    $_vars = $match[0];
    $ret = null;   
   
    if(     strtoupper($method)   ==  'POST' ) {
        $ret = _findRequestParam($_vars, $_POST);
    }
    elseif( strtoupper($method) == 'GET' ) {
        $ret = _findRequestParam($_vars, $_GET);
    }
    elseif( strtoupper($method) == 'COOKIE' ) {
        $ret = _findRequestParam($_vars, $_COOKIE);
   
    }
    elseif( strtoupper($method) == 'SESSION' ) {
        $ret = _findRequestParam($_vars, $_SESSION);
    }   
   
    if (! $ret )
          return $default;
    else
        return $ret;       
   
}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
    static $ret;
   
    if( array_key_exists($vars[$curr_key], $find_in) ) {
        if( count( $vars)-1 == $curr_key ) {
            $ret =  $find_in[$vars[$curr_key]];
        }
        elseif( $curr_key < count( $vars)-1 ) {
            _findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1  );       
        }   
    }

    return $ret;

}

?>



<br /><br /><br /><br />