Difference between revisions of "John's hacks"
From ProgClub
Line 5: | Line 5: | ||
// 2020-04-14 jj5 - it's important to handle this case... | // 2020-04-14 jj5 - it's important to handle this case... | ||
// | // | ||
− | if ( count( $list ) === 0 ) { return 'list | + | if ( count( $list ) === 0 ) { return 'list is empty'; } |
$result = 'my list: '; | $result = 'my list: '; |
Revision as of 10:35, 14 April 2020
I decided I might start documenting some hacks I've come across in my travels which I think are neat.
Removing last comma
// 2020-04-14 jj5 - it's important to handle this case... // if ( count( $list ) === 0 ) { return 'list is empty'; } $result = 'my list: '; foreach ( $list as $item ) { $result .= "$item, "; } // 2020-04-14 jj5 - the neat hack is dropping the last two characters here... // return substr( $result, 0, -2 ) . '.';
Although the whole thing can often be simplified as something like this (you might also need to check for an empty list):
return 'my list: ' . implode( ', ', $list ) . '.';