9
$p = (isset($_REQUEST["p"])?$_REQUEST["p"]:"");

This is the common line I usually use in my php code. I always assume is there a better(small and faster) way to write the same ?

7
  • 1
    You cannot do this shorter. Why you want it to be shorter? Not short enough? Commented Oct 17, 2012 at 11:48
  • The inline conditional is as short as possible. You can define a function of course. The problem is not your code but the fact that you don't know if the request parameter is actually set. Best and cleanest way for your case is probably to initialize needed variables by mapping request values to it using a function which checks for existence.
    – matthias
    Commented Oct 17, 2012 at 11:54
  • 1
    This might help you stackoverflow.com/a/12798041/1226894
    – Baba
    Commented Oct 17, 2012 at 12:03
  • So, as far as I know the answers given are correct, PHP has no great way to handle this. Just as a comment, this is a problem particular to the environment: as a programmer you have to get user inputs which may or may not have been passed to your page, and this is tedious and apparently inefficient.So, as a suggestion to the developers of PHP, wouldn't (at least in the $_GET context) it be great to have a primitive Commented Mar 15, 2015 at 7:17
  • Perhaps an operator "s=" . The conditional clause if ($_GET["may"] s= $have) would evaluate to true if both sides are set and satisfy ==. If either var is not set it would return false, not an error. It would save the programmer making multiple array references to get at it. I'm sure my idea would need some work. "s=" looks pretty strange as an operator to me. But it might possibly be worth the trouble for said PHP developers to consider the issue. Commented Mar 15, 2015 at 7:34

8 Answers 8

20

Create your own function :

function getIfSet(&$value, $default = null)
{
    return isset($value) ? $value : $default;
}

$p = getIfSet($_REQUEST['p']);

There's no other clean solution.

4
  • yes we can always create a function for that but this is the same as my statement. +1 for the first answer Commented Oct 17, 2012 at 11:55
  • 1
    @Champ - yes, it's the same thing, but it does neaten up the code if you need to repeat it a stack of times.
    – SDC
    Commented Oct 17, 2012 at 11:57
  • @Aelios till now the best answer I have is yours.but that's not new that was already known to me. so lets wait and see if someone can come up with a better code.... Commented Oct 17, 2012 at 12:07
  • @SDC if needs to repeat, then create another function for cheking an array of options...
    – NaN
    Commented May 5, 2017 at 13:20
9

EDIT: PHP 7 adds a null coalescing operator ("??")

$p = $_REQUEST["p"] ?? '';

https://www.php.net/manual/en/migration70.new-features.php


ORIGINAL:

if you want something shorter, and are content with an empty (string) default value, the following works:

$p = @$_REQUEST['p'];

@ is the error-suppression operator and will keep the expression from giving a warning if the value is not set.

http://www.php.net/manual/en/language.operators.errorcontrol.php

0
7

How more shorter do you want it?

Of course, if you are using this every time you access a request value, you should create a function somewhere and then use that:

function reqVal( $val, $default = "", $no_sql = true )
{
    $var = isset( $_REQUEST[$val] ) ? $_REQUEST[$val] : $default;
    $var = $no_sql ? nosql( $var ) : $var;
    return $var;
}

function getVal( $val, $default = "", $no_sql = true )
{
    $var = isset( $_GET[$val] ) ? $_GET[$val] : $default;
    $var = $no_sql ? nosql( $var ) : $var;
    return $var;
}

function postVal( $val, $default = "", $no_sql = true )
{
    $var = isset( $_POST[$val] ) ? $_POST[$val] : $default;
    $var = $no_sql ? nosql( $var ) : $var;
    return $var;
}

Now add the sql incjection check:

function nosql( $var )
{
    if ( is_array( $var ) ) {
        foreach ( $var as $key => $elem ) $var[$key] = nosql( $elem );
    } else if ( $var === null ) {
        return null;
    } else {
        if ( get_magic_quotes_gpc() ) $var = stripslashes( $var );
        $var = mysql_real_escape_string( $var );
    }
    return $var;
}

And access it always simple like this:

$p = reqVal( 'p', 0 );
$p = getVal( 'p', 'something', false );
$p = postVal( 'p' ); // or just forget the 2nd and 3rd parameter
5
  • I think this is the best solution but maybe with adding a default value parameter just like on Aelios' answer.
    – enenen
    Commented Oct 17, 2012 at 11:53
  • Edited the answer and yes, @Aelios did it first, if that's important ;)
    – Peon
    Commented Oct 17, 2012 at 11:56
  • Speed is the best parameter of you life !
    – Aelios
    Commented Oct 17, 2012 at 11:57
  • $default is Aelios' property ;) I give it to you Dainis Abols
    – Aelios
    Commented Oct 17, 2012 at 11:59
  • 1
    And one more thing if someone wants to copy/paste the function. Parameters are separated with a dot but not with a comma. Couldn't edit it because the fixing is very short. :)
    – enenen
    Commented Oct 17, 2012 at 12:01
2

The answers that wrap your existing code in a function are good - they do indeed tidy up the code if you've got a bunch of them.

However the better solution is to sanitize your entire request array based on a set of expected values before you start.

For example:

function sanitiseRequest() {
    $expected = array(
        'p' => '',
        'id' => 0,
        //etc
    );

    //throw away any input that wasn't expected...
    foreach($_REQUEST as $key=>$value) {
        if(!isset($expected[$key]) { unset $_REQUEST[$key]; }
    }
    //and for any expected values that weren't passed, set them to the defaults.
    foreach($expected as $key=>$defvalue) {
        if(!isset($_REQUEST[$key]) { $_REQUEST[$key] = $defvalue; }
    }
}

Then simply add a call to this function at the start of the code, and you won't need to worry about doing isset($_REQUEST[..]) anywhere else in your code.

This concept can be expanded to force the incoming arguments to be the correct data type as well, or any other data cleansing you may want to do. This can give you complete confidence that the incoming data is populated as you expect.

Hope that helps.

2

I usually take advantage of the fact that PHP is loosely typed and simply do:

$p = (string) $_REQUEST['p'];

This way, even if $_REQUEST['p'] is not set, an empty string still gets stored into $p. Keep in mind that this only works if your error handler ignores notices, as accessing an unset key will trigger an E_NOTICE along the lines of "undefined index".

4
  • And how would you know the difference between correct empty string and request variable error ?
    – Aelios
    Commented Oct 17, 2012 at 11:52
  • What do you mean by "request variable error"? How does Champ's own version know the difference? Commented Oct 17, 2012 at 11:55
  • $p = (string)@$_REQUEST["p"];
    – Udan
    Commented Oct 17, 2012 at 12:02
  • You mean "===" null? Because "", 0, false, they are all "==" to null. Also, when not set, $_REQUEST['p'] is already null, try var_dump-ing an unset _REQUEST variable. So how do you differentiate between an unset variable and a "request variable error"? Commented Oct 17, 2012 at 12:04
0

This is indeed so common, that i wonder there is no native way of doing it in PHP. Most developers write their own function to read safely from an array.

/**
 * Gets the value associated with the specified key from an array.
 * @param array $array The array to search for the key.
 * @param mixed $key The key of the value to get.
 * @param mixed $default The default value to return, if the
 *   specified key does not exist.
 * @return mixed Value that is associated with the specified
 *   key, or the default value, if no such key exists.
 */
function getValueFromArray($array, $key, $default = null)
{
  $containsKey = isset($array[$key]);
  if ($containsKey)
    return $array[$key];
  else
    return $default;
}

/**
 * Gets the value associated with the specified key from an array.
 * @param array $array The array to search for the key.
 * @param mixed $key The key of the value to get.
 * @param mixed $value Retrieves the found value, or is set to null
 *   if the key could not be found.
 * @return bool Returns true if the key could be found, otherwise false.
 */
public function tryGetValueFromArray($array, $key, &$value)
{
  $containsKey = isset($array[$key]);
  if ($containsKey)
    $value = $array[$key];
  else
    $value = null;
  return $containsKey;
}
5
  • 2
    Though I'm all for OO programming, if the OP asks for a shorter and faster way: functions and especially classes are not the way to go Commented Oct 17, 2012 at 12:01
  • @EliasVanOotegem - It depends on the point of view, once you have the function, the code you have to write is indeed shorter, just calling getValueFromArray($_REQUEST, 'p'). There is no native function as far as i know. Commented Oct 17, 2012 at 12:03
  • Sure, once the function is written out in full, you have to write a few chars less, but function calls are more expensive, and slower (compared to inline ternaries as the OP is using now). Seeing he's after a smaller and faster alternative, functions provide shorter code, but are slower. Just a side-note, that on the speed front Commented Oct 17, 2012 at 12:09
  • @EliasVanOotegem - first rule of optimisation: know what the real bottlenecks are in your system and fix them before you start worrying about the minute performance differences of one language construct over another.
    – SDC
    Commented Oct 17, 2012 at 12:21
  • @SDC: I thought the first rule was Premature optimization is the root of all evil ;-). I agree with you, but I think that's obvious when you see my answer. Still don't know why it got down-voted, though Commented Oct 17, 2012 at 12:39
0

You can find many examples of different solutions here http://php.net/manual/en/function.isset.php in the User Contributed Notes section.

Try this:

function get_if_set( $varname, $parent=null ) { 
    if ( !is_array( $parent ) && !is_object($parent) ) { 
        $parent = $GLOBALS; 
    }
    return array_key_exists( $varname, $parent ) ? $parent[$varname] : null; 
} 
0

This one works well for me. And you don't have to write the name twice. It won't change the var if it is already set. So it is safe to use for quick n dirty conversion of old application using register_globals.

function getIfSet($key, $default = null)
{
    global $$key;

    if(!isset($$key)){
        if(isset($_REQUEST[$key])){
            $$key=$_REQUEST[$key];
        }else{
            if(!is_null($default)){
                $$key = $default;
            }
        }
    }
}
function getIfSetArray($list){
    foreach($list as $item){
        getIfSet($item);
    }
}

getIfSet('varname');
getIfSetArray(['varname_1','varname_2']);

echo $varname;
echo $varname_1;

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.