isset PHP isset($_GET['something']) ? $_GET['something'] : ''

前端 未结 8 1453
清酒与你
清酒与你 2020-12-13 04:02

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see

8条回答
  •  长情又很酷
    2020-12-13 04:48

    If you want an empty string default then a preferred way is one of these (depending on your need):

    $str_value = strval($_GET['something']);
    $trimmed_value = trim($_GET['something']);
    $int_value = intval($_GET['somenumber']);
    

    If the url parameter something doesn't exist in the url then $_GET['something'] will return null

    strval($_GET['something']) -> strval(null) -> ""

    and your variable $value is set to an empty string.

    • trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
    • intval() if only numeric values are expected and the default is zero. intval(null) -> 0

    Cases to consider:

    ...&something=value1&key2=value2 (typical)

    ...&key2=value2 (parameter missing from url $_GET will return null for it)

    ...&something=+++&key2=value (parameter is " ")

    Why this is a preferred approach:

    • It fits neatly on one line and is clear what's going on.
    • It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
    • Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
    • It's compatible with older and newer php.

    Update Strict mode may require something like this:

    $str_value = strval(@$_GET['something']);
    $trimmed_value = trim(@$_GET['something']);
    $int_value = intval(@$_GET['somenumber']);
    

提交回复
热议问题