miami miami - 7 months ago 17
PHP Question

Echo datas from an array with php

I have the following array in php:

$stats = array(
"Item 1" => 20,
"Item 2" => 30,
"Item 3" => 66,
"Item 4" => 1

I need to echo these values, so I try this:

foreach ($stats as $stat => $data) {
echo '
<div class="col-sm-6">
<div class="widget">
<div class="widget-body p-t-lg">
<div class="clearfix m-b-md">
<h1 class="pull-left text-primary m-0 fw-500"><span class="counter" data-plugin="counterUp">'.$data.'</span></h1>
<div class="pull-right watermark"><i class="fa fa-2x fa-tv"></i></div>
<p class="m-b-0 text-muted">'.$stats[$stat].'</p>

But I have only the numerical values echoed.

Do you have the solution ?



Since you are using the foreach construct, $stat holds the keys and $data holds the values. So when saying echo $stats[$stat] is equivalent to echoing the value that has the key $stat. If you want to echo the keys you should do this : echo $stat.