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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.