Skip to content

Instantly share code, notes, and snippets.

@humbertocastelo
Created November 12, 2017 17:53
Show Gist options
  • Save humbertocastelo/610dd516f0784fe9cbd987159ecdeca0 to your computer and use it in GitHub Desktop.
Save humbertocastelo/610dd516f0784fe9cbd987159ecdeca0 to your computer and use it in GitHub Desktop.
Count Chars Delimiter
<?php
function count_chars_delimiter( string $str, string $delimiter = ',' ) {
$arr = [];
foreach ( array_filter( array_map( 'trim', explode( $delimiter, $str ) ), function( $v ) { return ( $v !== '' ); } ) as $value ) {
$arr[$value] = isset( $arr[$value] ) ? $arr[$value] : 0;
$arr[$value]++;
}
return $arr;
}
$str = ',2, 2 , 0,0 ,2,10,15,15,25,300,50,, , , ,,,,,,,,,,2,10';
$arr = count_chars_delimiter( $str, ',' );
print '<pre>' . var_export( $arr, true ) . '</pre>';
$str = '|3| 3 | 0|0 |3|11|16|16|26|301|51|| | | ||||||||||3|11';
$arr = count_chars_delimiter( $str, '|' );
print '<pre>' . var_export( $arr, true ) . '</pre>';
/*
array (
2 => 4,
0 => 2,
10 => 2,
15 => 2,
25 => 1,
300 => 1,
50 => 1,
)
array (
3 => 4,
0 => 2,
11 => 2,
16 => 2,
26 => 1,
301 => 1,
51 => 1,
)
//*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment