note 77236 added to language.types.array
| From: | Olegk at osu1 dot php dot net | Date: | Tue, 21 Aug 2007 09:59:05 +0000 |
| Subject: | note 77236 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129663@lists.php.net to get a copy of this message | ||
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;
}
?>
Hope this will help someone!
----
Server IP: 69.147.83.197
Probable Submitter: 89.218.217.179
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- https://master.php.net/note/edit/77236
Del: integrated -- https://master.php.net/note/delete/77236/integrated
Del: useless -- https://master.php.net/note/delete/77236/useless
Del: bad code -- https://master.php.net/note/delete/77236/bad+code
Del: spam -- https://master.php.net/note/delete/77236/spam
Del: non-english -- https://master.php.net/note/delete/77236/non-english
Del: in docs -- https://master.php.net/note/delete/77236/in+docs
Del: other reasons-- https://master.php.net/note/delete/77236
Reject -- https://master.php.net/note/reject/77236
Search -- https://master.php.net/manage/user-notes.php