1

Which loop can I use for an array in array with the output like this:

Coffee 1,90 | 2,30
Tea 1,70 | 2,20

This is the array

<?php
Array ( [coffee] => Array ( 
                    [Small] => 1,90
                    [Big] => 2,30
                ) 
    [tea] => Array ( 
                    [Small] => 1,70 
                    [Big] => 2,20 
                )
)
?>

I tried this

<?php
foreach ($array as $beverage => $types) {
    echo $beverage;
  foreach ($types as $type => $price) {
    echo $price;
  }
}
?>

But the output displays this

coffee 1,902,30
tea 1,702,20

How can I separate this like

Coffee 1,90 | 2,30
Tea 1,70 | 2,20

2 Answers 2

4
foreach ($array as $beverage => $types) {
    echo ucfirst($beverage) . implode(' | ', $types);
}
Sign up to request clarification or add additional context in comments.

Comments

0
foreach ($array as $beverage => $types) {
    echo $beverage;
    foreach ($types as $type => $price) {
        if ($price == end($types)) {

            echo $price."|";
        }
        else{
            echo $price;
        }
    }
}

Have a look at this : https://www.geeksforgeeks.org/php-end-function/

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.