Utility to join array as human readable list

This commit is contained in:
Tetrakern 2024-04-28 11:35:11 +02:00
parent c485c611a1
commit 9593ca2826
2 changed files with 40 additions and 0 deletions

View File

@ -202,6 +202,11 @@ The following list credits all third-party resources used in the Fictioneer them
License: [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/)<br> License: [CC BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/)<br>
Source: https://stackoverflow.com/a/4914807/17140970 Source: https://stackoverflow.com/a/4914807/17140970
* **Human readable list from array**<br>
Copyright: Derk-Jan Karrenbeld<br>
License: No license information provided (assumed public domain)<br>
Source: https://gist.github.com/SleeplessByte/4514697
## Fonts ## Fonts
* **Open Dyslexic 3**<br> * **Open Dyslexic 3**<br>

View File

@ -2961,3 +2961,38 @@ function fictioneer_find_user_by_display_name( $display_name ) {
// Not found // Not found
return null; return null;
} }
// =============================================================================
// JOIN ARRAYS IN SPECIAL WAYS
// =============================================================================
if ( ! function_exists( 'fictioneer_get_human_readable_list' ) ) {
/**
* Join string in an array as human readable list.
*
* @since 5.15.0
* @link https://gist.github.com/SleeplessByte/4514697
*
* @param array $array Array of strings.
*
* @return string The human readable list.
*/
function fictioneer_get_human_readable_list( $array ) {
// Setup
$comma = _x( ', ', 'Human readable list joining three or more items except the last two.', 'fictioneer' );
$double = _x( ' or ', 'Human readable list joining two items.', 'fictioneer' );
$final = _x( ', or ', 'Human readable list joining the last two of three or more items.', 'fictioneer' );
// One or two items
if ( count( $array ) < 3 ) {
return implode( $double, $array );
}
// Three or more items
array_splice( $array, -2, 2, implode( $final, array_slice( $array, -2, 2 ) ) );
// Finish
return implode( $comma , $array );
}
}