Reputation: 3638
here am trying to add a comma in the values got by the foreach loop. now the values are coming all together, but i want it to get echoed as comma separated. please suggest me what i gotta do . I know, i gotta use implode, but i don't know how to do it exactly in a loop.
foreach($_POST['insert'] as $interested) {
if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $interested)) continue;
echo $interested;
}
Upvotes: 0
Views: 3071
Reputation: 7824
Since $interested
clearly is a string, I assume you want to concatenate all these with ,
.
$counter = 0;
foreach($_POST['insert'] as $interested) {
if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $interested))
continue;
if($counter++)
echo ", ";
echo $interested;
}
This is a bit more performant than storing the values in a new array, however, you lose a bit of flexibility.
Upvotes: 0
Reputation: 490273
If you want to leave your code relatively untouched (though I fixed your confusing indentation)...
$interestedValues = array();
foreach($_POST['insert'] as $interested) {
if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $interested)) continue;
$interestedValues[] = $interested;
}
echo implode(',', $interestedValues);
...Or as one liners seem fashionable...
echo implode(',', preg_grep('/^[-A-Z\d., ]+$/iD', $_POST['insert']));
Upvotes: 6
Reputation: 2623
put all the values in an array and use JOIN to echo csv value:
$newarray = array();
foreach($_POST['insert'] as $interested) {
if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $interested)) continue;
$newarray[] = $interested;
}
echo JOIN(",",$newarray);
Upvotes: 0
Reputation: 3412
If you are interested only in specific values from $_POST['insert'], then create a new array and implode that:
$justSomeValues = array();
foreach($_POST['insert'] as $interested) {
if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $interested)) continue;
$justSomeValues[] = $interested;
}
echo implode(', ', $justSomeValues);
else, to implode the whole $_POST['insert'] do this:
echo implode(', ', $_POST['insert']);
Upvotes: 0
Reputation: 522125
This can even be done as a one-liner:
echo join(', ', array_filter($_POST['insert'],
function ($str) { return preg_match('/^[-A-Z0-9\., ]+$/iD', $str); }));
Upvotes: 2
Reputation: 18006
Just use as its syntax is
$array=array();
foreach($_POST['insert'] as $interested) {
if(!preg_match('/^[-A-Z0-9\., ]+$/iD', $interested)) continue;
$array[]=$interested;
}
echo implode(',',$array);
Upvotes: 0