Alex Maina
Alex Maina

Reputation: 306

concatinating two array elements with a string within a foreach loop

I am trying to combine two array elements with the string "OR" and create one string of elements.

The array looks like this: $myarray = array(2282396,1801345)

This is the code i have used.

$bool = ' OR ';
foreach($myarray as $element){

echo $element .= $bool;
}

I trying to get this output after looping using a foreach loop. 2282396 OR 1801345

However, the output i get looks like this: 2282396 OR 1801345 OR

How do i get rid of the 'OR' after the second element? Thanks in advance

Upvotes: 1

Views: 102

Answers (2)

pavel
pavel

Reputation: 27082

You have to check if you're in the first/last iteration or not.

$first = true;
$bool = ' OR ';
foreach ($myarray as $element) {
    if (!$first) {
        echo $bool;
    }
    echo $element; 
    $first = false;
}

If your array is indexed by numeric indexes 0-x, you an use

$bool = ' OR ';
foreach ($myarray as $key => $element) {
    if ($key > 0) {
        echo $bool;
    }
    echo $element; 
}

Upvotes: 2

dWinder
dWinder

Reputation: 11642

Use implode as:

echo implode(" OR ", $myarray);

Documentation implode

Live example: 3v4l

Upvotes: 2

Related Questions