Php - how do I display elements from an array with their values

I have this array:

Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)

      

How can I display it on the page? (preferably in descending order as follows):

\#cafc (2), #LFC (1), #SkySports (1)

      

thanks

+2


a source to share


4 answers


Sort the array first

arsort($arrayName);

      



Next, repeat the steps of the array and values .

foreach($arrayName as $key => $value)
{
    echo "$key ($value),";
}

      

+5


a source


Try using arsort to sort in descending order of values, and then loop through the array, printing out the key / value pairs as shown below:



arsort($original_array);
foreach($original_array as $k => $v) {
  echo $k.'('.$v.')';
}

      

+2


a source


If I understand your question correctly, use foreach

loop
in combination with arsort

:

arsort($array);
foreach($array as $k => $v) {
  printf('%s (%s)',
    htmlspecialchars($k),
    htmlspecialchars($v));
}

      

0


a source


arsort($array);
$output = array();
foreach($array as $k => $v) {
   $output[] = "$k ($v)";
}
print implode(", ", $output);

      

this will sort the array in reverse order and then create a new array with the data formatted however you like and then inject the output on a comma separated string. The rest of the answers so far will leave a dangling comma.

0


a source







All Articles