Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: Print ordered array

I have a simple PHP code where values from the array are ordered from largest to lowest.

I need them to print like basic HTML values with loop.

MY CODE:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$kosik = [
    [
      "typ" => "ovocna",
      "amount" => $ovocnaNUM
    ],
    [
      "typ" => "slana",
      "amount" => $slanaNUM,
    ],
    [
      "typ" => "sladka",
      "amount" => $sladkaNUM
    ]
];

usort($kosik, function ($a, $b) {
    return $b["amount"] - $a["amount"];
});

I need to echo them but when I use this I’ev got error:

foreach($kosik as $key => $value) {
    echo "$key - $value <br>";
}

ERROR: Array to string conversion

But when I use this:

foreach($kosik[0] as $key => $value) {
    echo "$key - $value <br>";
}

I’ve got no errors but only the first value is printed.

Is there any option how I can print all values with foreach or loop like is printed one value in code above?

>Solution :

One way, simply address the $value array using its members

foreach($kosik as $key => $value) { 
    echo "$key - $value[typ], $value[amount] <br>";  
}

NOTE that inside a double quoted string you address the array slightly differently, you dont use the quotes around the occurance name.

Possibly more flexibly you could use a double loop, specially if you dont know or cannot guarantee the occurances will always be there

$str = '';
foreach($kosik as $key => $value) { 
    $str .= "$key - ";
    foreach ( $value as $val ) {
        $str .= "$val, ";
    }
    $str = rtrim($str, ', ');  remove trailing comma
    $str .= '<br>';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading