Jump to content

Array Keys


socalnate

Recommended Posts

Been trying to figure out an array issue.  For some reason when I echo $key it's echoing "Array".  I want it to return the key (in this case adventure).  Help appreciated...

 

<?php
$action_percent = 1;
$adventure_percent = 20;

$genre_array = array(
  'action'=>$action_percent,
  'adventure'=>$adventure_percent
);
echo $genre_array['action']; 
echo $genre_array['adventure'];

$max_value = max($genre_array);
echo $max_value;

$key = array_keys($genre_array, max($genre_array));
echo $key;
?>

Link to comment
https://forums.phpfreaks.com/topic/75999-array-keys/
Share on other sites

Looks like you might be looking for a FOREACH loop here. ARRAY_KEYS is returning an array. To see it, try this code real quick:

 

<?php
$action_percent = 1;
$adventure_percent = 20;

$genre_array = array(
 'action'=>$action_percent,
 'adventure'=>$adventure_percent
);
echo $genre_array['action']; 
echo $genre_array['adventure'];

$max_value = max($genre_array);
echo $max_value;

$key = array_keys($genre_array, max($genre_array));
echo "<pre>";
print_r ($key);
echo "</pre>";
?>

 

To use a FOREACH loop to do the same thing, but control the echoing of each element, do this:

 

<?php
$action_percent = 1;
$adventure_percent = 20;

$genre_array = array(
 'action'=>$action_percent,
 'adventure'=>$adventure_percent
);
echo $genre_array['action']; 
echo $genre_array['adventure'];

$max_value = max($genre_array);
echo $max_value;

$key = array_keys($genre_array, max($genre_array));
foreach ($key as $value) {
   echo "$value<br />";
}
?>

 

And of course, building from there, you can dig deeper into the array structure to echo out anything you desire.

 

PhREEEk

 

Link to comment
https://forums.phpfreaks.com/topic/75999-array-keys/#findComment-384687
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.