PHP类型转换null或int

PHP类型转换null或int,php,typecasting-operator,Php,Typecasting Operator,我想让变量为int,除非该变量为null。 这是我修理它的方法,但肯定有更好的解决办法 if ($answer == null) { $all_questions[] = array ( 'object_id' => (int) $stored_question->getObjectId(), 'question_code' => $stored_question->getQuestionCode(),

我想让变量为int,除非该变量为null。
这是我修理它的方法,但肯定有更好的解决办法

if ($answer == null) {
      $all_questions[] = array (
        'object_id'     => (int) $stored_question->getObjectId(),
        'question_code' => $stored_question->getQuestionCode(),
        'answer'        => $stored_question->getAnswer()
      );
    }
    else{
      $all_questions[] = array (
        'object_id'     => (int) $stored_question->getObjectId(),
        'question_code' => $stored_question->getQuestionCode(),
        'answer'        => (int) $stored_question->getAnswer()
      );
至少我希望有,因为这似乎是多余的。

试试这个:

$all_questions[] = [
    'object_id'     => (int) $stored_question->getObjectId(),
    'question_code' => $stored_question->getQuestionCode(),
    'answer'        => empty($answer)? $stored_question->getAnswer(): intval($stored_question->getAnswer())
];

首先声明您想要从两个密码中获得的共同想法

$all_questions[] = array (
        'object_id'     => (int) $stored_question->getObjectId(),
        'question_code' => $stored_question->getQuestionCode(),
      );
这取决于特定的条件

$all_questions['answer'] = (is_null($answer)) ? 
  $stored_question->getAnswer() : (int) $stored_question->getAnswer() : 

是否为null($x)?$x:intval($x)
,但正如我在您的案例中看到的那样,
getAnswer
返回一个整数作为字符串或null,您应该将返回值强制转换为null。请注意,对于PHP认为为
false
的任何
$answer
,问题中的代码不会执行Wouter要求的操作[除非变量为null,否则为int]。因为在PHP中,null==false。在编写上述代码之前,请执行以下任一操作:
$answer=0
$answer=“0”
$answer=0.0
$answer=false。这些都不是“null”,但它们都是
==null
。要测试空值,请使用
==null
,不要使用
==null
。不要使用
空值
。对于可能让您吃惊的实体,如字符串
“0.0”
,返回true。所以这个答案不符合要求,;它将返回ints或null以外的值。如图所示,如果您想测试null,那么就测试null
为空
===null
是两种方法。完全符合这个问题。FWIW,对于大多数这样编写代码的人来说,
$answer
是要返回的值,不需要再次调用
getAnswer()
。在这种情况下,代码简化为
…=是空的($答案)?null:(int)$answer。选项:无需将最终财产转让分开;这可以作为阵列初始化的一部分来完成。我通常先做“修复”:如果(!is_null($answer))$answer=(int)$answer$所有问题[]=数组('object\u id'=>…,'answer'=>$answer)