开发者

Does there exist a shorter if statement in PHP?

Is it possible to rewrite this to be shorter somehow?

if (isset($_POST['pic_action'])){
  $pic_action=$_POST['pic_action'];
}
else { 
  $pic_action=0;
}

I have seen it somewhe开发者_如何学Pythonre but forgot... :/

BTW, please explain your code also if you like!

Thanks


You could use the conditional operator ?::

$pic_action = isset($_POST['pic_action']) ? $_POST['pic_action'] : 0;

The conditional operator expression expr1 ? expr2 : expr3 evaluates to the return value of expr2 if the evaluated return value of expr1 is true; otherwise the expression evaluates to the evaluated return value of expr3. So if isset($_POST['pic_action']) evaluates to true, the whole expression evaluates to the evaluated value of $_POST['pic_action'] and to the evaluated value of 0 otherwise.

So in short: if isset($_POST['pic_action']) is true, $pic_action will hold the value of $_POST['pic_action'] and 0 otherwise.


Gumbo's answer is probably the best way.

It can also be written as:

$pic_action = 0;
if (isset($_POST['pic_action'])){
    $pic_action=$_POST['pic_action'];
}


$pic_action=(isset($_POST['pic_action']))?($_POST['pic_action']):0;


$pic_action = array_get($_POST, 'pic_action', 0);

The line above requires the array_get function defined below. Source from Kohana's Arr class. Very small and generic function. Can be used on all arrays, e.g. $_GET.

/**
 * Retrieve a single key from an array. If the key does not exist in the
 * array, the default value will be returned instead.
 *
 * @param   array   array to extract from
 * @param   string  key name
 * @param   mixed   default value
 * @return  mixed
 */
function array_get(array $array, $key, $default = NULL)
{
    return isset($array[$key]) ? $array[$key] : $default;
}


Longer, but reusable:

$pic_action = QueryPost('pic_action', 0);

function QueryPost($name, $default='', $valid=false) {
    if (!isset($_POST[$name])) return $default;
    if (($valid) and (empty($_POST[$name]))) return $default;
    return $_POST[$name];
}

Or you could have the QueryPost function do a form of validation while you're at it.

$pic_action = QueryPost('pic_action', 'int', 0);

function QueryPost($name, $rule, $default='', $valid=false) {
    // this shouldn't be too hard to write
}


You can do:

$_POST['pic_action'] = isset($_POST['pic_action']) ? $_POST['pic_action'] : 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜