0

I have a unique problem.

I have a few arrays that each have 2 items and are in the following form:

$arr=Array
(
    [TEAM1] => 113.03
    [TEAM2] => 103.52
)

I am trying to create a function that given the array ($arr) and one of the keys (TEAM1), it would return the other key (TEAM2). The array will always only have 2 values and the key you put in will always exist.

My problem is that I have no idea how to start this.. if the key was 0 or 1 it would be easy selecting the other row but for this I am not sure how to start

4
  • 1
    $str = 'TEAM2'; $notTeam2 = array_diff_key($arr, [$str => null]); Demo Commented Sep 22, 2015 at 21:14
  • 1
    $result = preg_grep("/$key/", array_keys($arr), PREG_GREP_INVERT); Commented Sep 22, 2015 at 21:17
  • @MarkBaker: Your solution worked. If you post it as answer, ill approve it. Also how do I just return the value (i.e. 113.03) and not the whole array Commented Sep 22, 2015 at 21:24
  • 1
    unset $arr[$key]; reset($arr); $value = current($arr); should do it. Commented Sep 22, 2015 at 21:37

1 Answer 1

1

To get the key that isn't $str:

$str = 'TEAM2';
$notTeam2 = array_diff_key($arr, [$str => null]);

Using array_dereferencing to get the value without needing to know the key:

$notTeam2Value = array_values($notTeam2)[0];

Demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.