1

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

2 Answers 2

2

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; 
}
Sign up to request clarification or add additional context in comments.

3 Comments

@dWinder: sure, I know. The OP asks for foreach loop. It can be simplified code in question, probably doesn't need to use just echo, etc. The OP asks for the foreach loop, so there is an answer with foreach loop.
Works like a charm @panther. I am accepting this as an answer
I don't think the OP knew what he wants - this is our job to not just answer him but also to teach him - as sometime he doesn't know what he need
2

Use implode as:

echo implode(" OR ", $myarray);

Documentation implode

Live example: 3v4l

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.