2016-05-26 91 views
0

我想讓一個變量爲int,除非變量爲null。
這是我固定atm的方式,但必須有更好的解決方案。PHP類型爲null或int

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

至少我希望這是因爲這似乎是多餘的。

+0

'is_null($ x)的希望? $ x:intval($ x)',但正如我在您的案例中看到的那樣'getAnswer'返回一個整數作爲字符串或null,您應該將返回值轉換爲 – cske

回答

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

thx完美作品 – Wouter

+0

歡迎您:) –

0

首先聲明常見認爲你從兩個codition

$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() : 
相關問題