有条件的三元运算符故障(PHP)

Ang*_*tis 0 php ternary-operator

我建立了一个功能来改变一个给定的Y-m-d日期是这样的:2016-07-02以这种格式:July 2nd

代码

// Format the given Y-M-D date
function format_date($date) {
    // Parse the date
    list($year, $month, $day) = array_values(date_parse($date));

    // Give the appropriate subscript to the day number
    $last_char = substr($day, -1);
    $pre_last_char = (strlen($day) > 1) ? substr($day, -2, -1) : null;
    $subscript = ($last_char === "1") ? "st" :
                 ($last_char === "2") ? "nd" :
                 ($last_char === "3") ? "rd" : "th";
    $subscript = ($pre_last_char === "1") ? "th" : $subscript;
    $day .= $subscript;

    // Get the month's name based on its number
    $months = [
        "1" => "January",
        "2" => "February",
        "3" => "March",
        "4" => "April",
        "5" => "May",
        "6" => "June",
        "7" => "July",
        "8" => "August",
        "9" => "September",
        "10" => "October",
        "11" => "November",
        "12" => "December"
    ];
    $month = $months[$month];

    // Omit the year if it's this year and assemble the date
    return $date = ($year === date("Y")) ? "$month $day $year" : "$month $day";
}
Run Code Online (Sandbox Code Playgroud)

该功能按预期工作,但有一个陷阱。第一个条件三元运算符,用于$subscript返回"rd"1和结尾的每个数字2

例:

echo format_date("2016-01-01"); // It will output January 1rd
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Ale*_*lex 5

文档内容如下:

注意:建议您避免“堆叠”三元表达式。在单个语句中使用多个三元运算符时,PHP的行为是不明显的:

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
Run Code Online (Sandbox Code Playgroud)