Is there a better way to write this name conversion function in php?

81 views Asked by At

Persian day names are different than English, and also week starts Saturday. So I have this weekday name and number conversion function:

function getDayNames($day, $shorten = false, $len = 1, $numeric = false)
{
    $ret = '';
    switch ( strtolower($day) ) {
        case 'sat': case 'saturday':  $ret = 'شنبه'; $n = 1; break;
        case 'sun': case 'sunday':    $ret = 'یکشنبه'; $n = 2; break;
        case 'mon': case 'monday':    $ret = 'دوشنبه'; $n = 3; break;
        case 'tue': case 'tuesday':   $ret = 'سه شنبه'; $n = 4; break;
        case 'wed': case 'wednesday': $ret = 'چهارشنبه'; $n = 5; break;
        case 'thu': case 'thursday':  $ret = 'پنجشنبه'; $n = 6; break;
        case 'fri': case 'friday':    $ret = 'جمعه'; $n = 7; break;
    }
    return ($numeric) ? $n : (($shorten) ? substr($ret, 0, $len) : $ret);
}

and I wanna know if there is a better way to rewrite this. Using switch is not ideal.

Thanks in advance.

1

There are 1 answers

2
Connor Peet On BEST ANSWER

Possibly arrayify it:

function getDayNames($day, $shorten = false, $len = 1, $numeric = false) {
    $days = array(
        'sat' => 'شنبه',
        'sun' => 'یکشنبه',
        'mon' => 'دوشنبه',
        'tue' => 'سه شنبه',
        'wed' => 'چهارشنبه',
        'thu' => 'پنجشنبه',
        'fri' => 'جمعه'
    );

    $key = substr(strtolower($day), 0, 3);
    if (array_key_exists($key, $days) {
        $ret = $days[$key];
    } else {
        throw new Expection('Day ' . $day . ' not found!');
    }

    return ($numeric) ? (array_search($key, array_keys($days)) + 1) : (($shorten) ? substr($ret, 0, $len) : $ret);
}