0

I try to get the result

danny love to eat orange and banana and grapes

Is it possible to get it through the function foreach

my Sample Code

$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ';

//NOT THIS METHOD
// echo $var [0];
// echo ("and");
// echo $var [1];
// echo ("and");
// echo $var [2];

//Through this method
foreach ($var as $fruit) {
echo $fruit ;
echo ("and");
}

The result I get if i use foreach

danny love to eat orange and banana and grapes and

What's wrong ? :(

3 Answers 3

4

You're echoing 'and' one too many times. You don't want to echo 'and' if you're on the last element.

Try this instead.

$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ' .implode('and',$var);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it helped me a lot
2

@bassxzero's answer is a great (In fact, I would recommend doing it that way over this way), but I wanted to show another way you could do this if you wanted to use a foreach loop still if you wanted to.

$var = array ("orange","banana","grapes");
$string = 'danny love to eat ';

//Through this method
foreach ($var as $fruit) {
    $string .= $fruit. " and ";
}
$string = substr($string, 0, -5);
echo $string;

In my code, we are building a string that contains all the words that you want seperated by " and ". Then as soon as the loop is done, we use substr() to remove the very last " and " so that $string equals the string you were expecting.

1 Comment

No problem at all.
0

Another solution could be

$var = array (" orange "," banana "," grapes ");
$str = 'danny love to eat ';
$total = count($var); // counts your aray
foreach ($var as $fruit) {
    $total--; // decrements $total value
    $str .= $total < 1 ? $fruit : $fruit.' and '; //if $total is reduced to 0 your loop is on the last repeat, so dont print 'and' anymore
}
echo $str;

Anyway implode way is the most elegant here.

1 Comment

could also do $str .= $total === 0 ? $fruit : $fruit.' and ';

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.