0

I have a php/mysql database website that isn't working and I'm hoping for a little help.

This is the effect I would like to achieve: I have 3 categories (commenter, visitor, and owner) each with a different integer values that is pulled from a database ($total1, $total2, $total3 respectively). I want to compare the 3 values of $total and find out which one is the highest. If $total2 is the highest, I want the value of $Popular to be set at "visitor"; if $total3 is the highest, I want $Popular to be "owner).

I tried to do this:

$Popular_array = array ('commenter' => $total1, 'visitor' => $total2, 'owner' => $total3);
$Popular = max (array_keys ($Popular_array));

but this was the result when I output the variables using print_r:

Array ( [commenter] => 50 [visitor] => 13 [owner] => 38 ) 
owner

I have already read Search for highest key/index in an array but it is not quite what I'm looking for because the solution above does not work. What am I doing wrong? Thanks!

Community
  • 1
  • 1
GK79
  • 241
  • 1
  • 4
  • 17

2 Answers2

1

The problem is that you are looking for the maximum key instead of value, which will not return the desired result. You would need to use array_values() then array_search():

$Popular_array = array ('commenter' => $total1, 'visitor' => $total2, 'owner' => $total3);
$Popular = array_search (max (array_values ($Popular_array)), $Popular_array);
Anonymous
  • 11,748
  • 6
  • 35
  • 57
1

As I said in the comments, you're comparing your keys, not values. So you need to fetch the key of the highest-valued array member. You can do it like this:

$Popular = array_search( max($Popular_array), $Popular_array );

See it in action here: http://ideone.com/Np6xp6

Shomz
  • 37,421
  • 4
  • 57
  • 85