Search code examples
phptypecasting-operator

PHP typecasting null or int


I want to let a variable be an int unless the variable is null.
This is the way I fixed it atm but there's got to be a better solution.

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()
      );

At least I hope there is because this seems redundant.


Solution

  • try this:

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