If null use other variable in one line in PHP

前端 未结 12 768
说谎
说谎 2020-12-29 01:47

Is there in PHP something similar to JavaScript\'s:

alert(test || \'Hello\');

So, when test is undefined or null we\'ll see Hello, otherwis

12条回答
  •  灰色年华
    2020-12-29 02:24

    One-liner. Super readable, works for regular variables, arrays and objects.

    // standard variable string
    $result = @$var_str ?: "default";
    
    // missing array element
    $result = @$var_arr["missing"] ?: "default";
    
    // missing object member
    $result = @$var_obj->missing ?: "default";
    

    See it in action: Php Sandbox Demo

提交回复
热议问题