1

I have

$max = max($a, $b, $c);

which results, lets say 30. I don't know which variable($a or $b or $c) gives the result 30. From this result(30) i have to find the variable name.

The result should be $a or $b or $c.How can I find this??

NOTE: Find the max is only a sample case.I need the variable name from a value from a group of variables.

5
  • 3
    Requiring knowledge about a concrete variable name from within the code is rarely a good idea. You may want to add why you think you need this. Commented May 20, 2014 at 12:17
  • Use an array and a loop instead. Why would you need access to a variable name rather than the value? Commented May 20, 2014 at 12:18
  • why you want to know the variable name? You can check in reverse order like if($a==$max) using conditional operator... Commented May 20, 2014 at 12:22
  • should be strange, but is there any way? Eg:case:A get 20 mark, B get 40 mark, C get 25 mark.I have to find the student who got maximum from mark.Consider mark is unique. Commented May 20, 2014 at 12:26
  • If you have students, just add them to an array and sort this. The first (or last), after sorting, is the student you're looking for. Commented May 20, 2014 at 12:28

4 Answers 4

3
$max = max($a, $b, $c);

// Create an array so we can find the name for each variable we're checking
$var_array = array(
    '$a' => $a,
    '$b' => $b,
    '$c' => $c,
);

// Use the array search function to find our key: http://php.net/array_search
$max_var_name = array_search($max, $var_array, true);
Sign up to request clarification or add additional context in comments.

1 Comment

@next2u In case you're curious angel's solution returns an array of matching keys, so if 2 or 3 people have the same max score it'll show all of their names, mine stops looking at the first result. I would seriously recommend considering that as a better option.
3
$array = array('a'=> $a, 'b'=> $b, 'c'=> $c);

$maxs = array_keys($array, max($array));

Comments

0
$a = 30; $b=20; $c=40;

$arr[$a] = '$a'; $arr[$b] = '$b'; $arr[$c] = '$c';

echo 'max val='.$max = max($a, $b, $c);

echo 'var name='.$arr[$max];

Comments

-1

I am not asking you why? Here is the solution that I think will work

use get_defined_vars() function which will return all the defined variables in an array. Then check the value of all the variable names with the result value (of which you want to know the variable).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.