0

I'm dealing with this program,Here I'm trying to separate the string email,by ',',and then I'm storing in the array,then appending with 'city' in foreach..

$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
     $result .= " city = '$v' ";
     echo $result;
}

I'm getting the result as

city = 'aa' city = 'aa' city = 'bb' city = 'aa' city = 'bb' city = 'cc' city = 'aa' city = 'bb' city = 'cc' city = 'dd'

but I want it to be,,

city = 'aa' city = 'bb' city = 'cc' city = 'dd' 

Is my code wrong?..please guide me..

2
  • Don't put the echo in the loop. That's why it outputs the progressively growing list. Commented Oct 19, 2013 at 3:57
  • Seems like the rest of the squadron has just flown in. Commented Oct 19, 2013 at 4:08

5 Answers 5

2

Move the echo out of the loop since you are building the whole string in the loop, this will echo the string every time.

$result="";
foreach($a as $v)
{
     $result .= " city = '$v' ";

}

     echo $result;  // move it here
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe I should put in the same answer too. (joking)
@user2810964 You know what to do.
@Hanky웃Panky SO can be so funny sometimes hehehe (+1) ;-)
0

You are getting the result as per your code, you echo the result in each loop execution.

So for getting the final values inside $result, echo it outside the loop.

foreach($a as $v)
{
    $result .= " city = '$v' ";
}
echo $result;

Comments

0

Remove the string concatenation in the result

 $email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
     $result = " city = '$v' ";//changed $result .= " city = '$v' "; to $result = " city = '$v' ";
     echo $result;
} 

Comments

0

You are echo $rresult in foreach so your string or variable is repeat. Please try below code :

$email='aa,bb,cc,dd';
$a=explode(',',$email);

$result="";
foreach($a as $v)
{
    $result .= " city = '$v' ";     
}
echo $result;

Comments

0

Remove string concate..

$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
     $result = " city = '$v' ";  // remove string concate..
     echo $result;
}


Another way is echo outside the foreach loop...

$email='aa,bb,cc,dd';
$a=explode(',',$email);
//echo $a[2];
$result="";
foreach($a as $v)
{
     $result .= " city = '$v' "; 
}

echo $result; // echo outside the foreach loop


Output

city = 'aa' city = 'bb' city = 'cc' city = 'dd' 

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.