Bala
Bala

Reputation: 3638

How to implement implode in foreach?

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

Answers (6)

janoliver
janoliver

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

alex
alex

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

Arfeen
Arfeen

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

Vlad Balmos
Vlad Balmos

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

deceze
deceze

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

Awais Qarni
Awais Qarni

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

Related Questions