John's hacks
From ProgClub
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 missing'; }
$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 );