|
Posted by Mike P2 on 05/10/07 20:44
I wasn't going to suggest using the ternary operator because Dean said
he is a beginner and is following a book. I assume that book has this
planned out and will introduce that operator at a later time, and the
purpose of the example he is having trouble with is to introduce him
to some other concept. I just didn't want to confuse him.
Also, Toby A Inkster, that function is a good idea, but it will result
in a notice anyway if the variable is undefined. It will issue a
notice anyway because when you put the undefined variable in the
function call, php is trying to pass the value of that variable, so it
throws a notice right there. It could be otherwise written with
strings passed:
function ifsetor2()
{
$fArgv = array();
$fArgv = func_get_args();
$fArgc = func_num_args() - 1;
for( $i = 0; $i < $fArgc; ++$i )
{
$glStr = ( $s = strpos( $fArgv[$i], '[' ) ) !== false
? substr( $fArgv[$i], 0, $s )
: $fArgv[$i];
$glStr = ( $s = strpos( $glStr, '.' ) ) !== false
? substr( $glStr, 0, $s )
: $glStr;
eval( "global \$$glStr;
\$stuff = isset( \${$fArgv[$i]} )
? \${$fArgv[$i]}
: false;" );
if( $stuff !== false )
return $stuff;
}
return $fArgv[$fArgc];
}
This will allow you to use more than one candidate as you mentioned,
and PHP will not issue a notice this way. The parameters are N strings
that are the names of variables (without $, and can be an array, but
then the index [if a string] needs to be in single or double quotes),
and finally a string to return if none are set. This new function
should work with fields of objects, too.
example:
echo ifsetor2( '_GET["search"]', '_GET['submit']', 'none' );
-Mike PII
Navigation:
[Reply to this message]
|