Reputation: 21
I have a script I am working on for an automated task, so I am not really worried about clean code as it will be used only one time anyways.
The script reads off of a flat file and stores the information into an array which will later be used to read something out of a database.
However, I only want numeric data, so I used preg_replace() and a comma. My code is as follows.
These are read from values in the flat file using a loop.
$store = array();
$store[] = 111;
$store[] = 2;
$store[] = 4;
$store[] = 55;
$store[] = 66;
$store[] = 'Kilory';
$store[] = 9090;
$theList[$i] = preg_replace( '/[^0-9,]/u', '', implode( ',', $store ) );
unset( $store );
the result that this gives me is 0,2,4,55,66,,9090. If I was to try and use the information for use in a mysql IN() statement, it would spit an error back at me due to having two commas next to each other. What is the best way to remove duplicates next to each other?
Thank you!
Upvotes: 2
Views: 332
Reputation: 4028
PHP offers a filter function for that purpose:
$store = array();
$store[] = 111;
$store[] = 2;
$store[] = 4;
$store[] = 55;
$store[] = 66;
$store[] = 'Kilory';
$store[] = 9090;
$theList[$i] = implode(',', array_filter($store, 'is_numeric'));
unset($store);
Upvotes: 1
Reputation: 23787
duplicate comma including heading and trailing commas you can remove with $string = trim(preg_replace('#,{2,}#', ',', $string), ',');
.
Upvotes: 3