PHP typecasting null or int

Wouter picture Wouter · May 26, 2016 · Viewed 9.2k times · Source

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.

Answer

shivani parmar picture shivani parmar · May 26, 2016

First Declare Common think which you want from both codition

$all_questions[] = array (
        'object_id'     => (int) $stored_question->getObjectId(),
        'question_code' => $stored_question->getQuestionCode(),
      );

Which will depend on certain condition

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