Home > Net >  How to compare array values preserving keys?
How to compare array values preserving keys?

Time:10-24

I can't figure out how to check if array values are equal or not. Array always have only 2 keys, need to preserve them, keys unknown. E.g.:

$arr = array(
    5 => 180,
    3 => 120
);

if ($arr['key1_value'] != $arr['key2_value']) {
    $variable = $arr['key1'];
} else {
    $variable = ($arr['key1']   $arr['key2']) / 2;
}

CodePudding user response:

Use array_values() or array_keys() to get an array of the value in this array, but with a zero based (predictable) set of keys

$arr = array(
    5 => 180,
    3 => 120
);
#$v = array_values($arr);
$v = array_keys($arr);

if ($v[0] != $v[1]) {
    $variable = $v[0];
} else {
    $variable = ($v[0]   $arr[1]) / 2;
}

CodePudding user response:

This is not so clear... But if I refer to your comments, I should say that this approach could solve your problem:

// Here is your data
$arr = array(
    5 => 180,
    3 => 120
);

// You seem to be interested by keys as a return, so flip the array
$flip = array_flip($arr);

// Return a mean or a key, depending on comparison between flip and original array
$variable = (count($flip) < 2) ? array_sum(array_keys($arr))/2 : array_shift($flip);

To clarify the last line:

  • If the number of values in $flip is lower, that means your two values are equals (because two same keys can not be accepted after the flip): in this case, we return the mean of keys (here it works because you confirmed that keys are always intergers)
  • If not, the first key is returned (I think it is what you expected, but not sure)

EDIT: In my proposition, I did a count on the array. As you said it is always 2 compared values, I replaced it directly by "2".

  • Related