Commit 05263692 by pana1990 Committed by Qiang Xue

Fixes #5938: add sentence method in Arrayhelper for convert the array to a comma-separated sentence

parent 88caccd6
......@@ -566,4 +566,64 @@ class BaseArrayHelper
return true;
}
}
/**
* Converts the array to a comma-separated sentence where the last element
* is joined by the connector word.
*
* Below are some usage examples,
*
* ~~~
* // $array = ['Spain', 'France', 'Italy'];
* // working with array
* \yii\helpers\ArrayHelper::sentence($array);
* // output : Spain, France, and Italy
*
* // working with options for change behavior
* \yii\helpers\ArrayHelper::sentence($array, ['last_word_connector' => ' or ']);
* // output : Spain, France or Italy
* ~~~
*
* @param array $array the array to be converted into an string
* @param array $options the options in terms of name-value pairs. The following options
* are specially handled:
*
* - words_connector: The sign or word used to join the elements in arrays with two or
* more elements. By default ', ''.
*
* - two_words_connector: The sign or word used to join the elements in arrays with two
* elements. By default ' and '.
*
* - last_word_connector: The sign or word used to join the last element in arrays with
* three or more elements. By default ', and '.
*
* - locale: If i18n is available, you can set a locale and use the traslation file defined
* on the path 'messages/yii.php'.By default language defined in configuration file.
*
* @return string
*/
public static function sentence($array, $options = [])
{
$default_options = [
'words_connector' => ', ',
'two_words_connector' => ' and ',
'last_word_connector' => ', and ',
'locale' => Yii::$app->language
];
$options = array_merge($default_options, $options);
$count = count($array);
switch ($count)
{
case 0:
return '';
case 1:
return $array[0];
case 2:
return $array[0] . \Yii::t('yii', $options['two_words_connector'], [], $options['locale']) . $array[1];
default:
return implode($options['words_connector'], array_slice($array, 0, -1)) . \Yii::t('yii', $options['last_word_connector'], [], $options['locale']) . $array[$count - 1];
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment