Can I define a variable in a PHP if condition?

前端 未结 5 2250
失恋的感觉
失恋的感觉 2020-12-05 23:17

For example, can I do:

if ($my_array = wp_get_category($id)) {
    echo \"asdf\";
} else {
    echo \"1234\";
}

If nothing is returned by t

5条回答
  •  醉酒成梦
    2020-12-05 23:53

    Yes, that will work, and the pattern is used quite often.

    If $my_array is assigned a truthy value, then the condition will be met.

    CodePad.

    The inverse is also true...

    If nothing is returned by the function, I want to go into the else statement.

    A function that doesn't return anything will return NULL, which is falsey.

    CodePad.

提交回复
热议问题