Reputation: 4771
I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the highest value?
Thanks in advance.
Upvotes: 2
Views: 3635
Reputation: 239382
Given four variables:
$a = 1;
$b = 3;
$c = 4;
$d = 2;
You can use compact
to turn them into an associative array:
$array = compact('a', 'b', 'c', 'd');
var_dump($array); // array('a' => 1, 'b', => 3, 'c' => 4, 'd' => 2);
And then find the maximum key/value:
$max_key = $max_value = null;
foreach ($array as $key => $value) {
if (is_null($max_value) || $value > $max_value) {
$max_key = $key; $max_value = $value;
}
}
Upvotes: 2
Reputation:
Here is a solution to the question you asked:
$arr = compact('v1', 'v2', 'v3', 'v4');
arsort($arr);
$name = key($arr);
// get the value: ${$name}
However, having the variables stored in an array in the first place would make more sense. A better setup would be:
$arr = array('v1' => 543, 'v2' => 41, 'v3' => 1, 'v4' => 931);
arsort($arr);
$name = key($arr);
// get the value: $arr[$name]
Upvotes: 10