PHP类型转换为null或int

时间:2016-05-26 07:16:16

标签: php typecasting-operator

我想让变量为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()
      );

至少我希望有,因为这似乎是多余的。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

首先宣布你想要从两个编码中共同思考

$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() :