3

I combined two arrays to create the following array, named $group_wages_array:

Array ( [1] => 500 [4] => 44 [6] => 80 [3] => 11.25 )

I am trying to test if the array key matches X, set a variable as it's value. Here's what I have:

NOTE: This whole thing is executed in a while loop, so the value of $thegroup['group_id'] will change. I've set it's value as "6" for this example.

$thegroup['group_id'] = "6" // This particular group (for simplicity)

if (array_key_exists($thegroup['group_id'], $group_wages_array)) {

    $this_wages = // Need this to be 80... how do I do it?

}

So, how do I get $this_wages to equal the key value?

3
  • That should work. If not, try casting $thegroup['group_id'] to an int. Commented Oct 12, 2011 at 21:38
  • You can use anything you want as an array key, as long as PHP can typecast it to a string or an integer. This includes embedding one array reference inside another: $outer[$inner[1]], so $group_wages_array[$thegroup['group_id']]. Commented Oct 12, 2011 at 21:46
  • +1 for going into detail about what your variables are and how they're being used. I wish more people would do that instead of just dumping code without sufficient context. Commented Oct 12, 2011 at 22:43

2 Answers 2

8

You just use the key from the array to get it:

$thegroup['group_id'] = "6" // This particular group (for simplicity)

if (array_key_exists($thegroup['group_id'], $group_wages_array)) {
    $this_wages = $group_wages_array[$thegroup['group_id']];
}

Also, the array keys are not 0,1,2,etc because you explicitly set them in Array ( [1] => 500 [4] => 44 [6] => 80 [3] => 11.25 )

0
1

You are trying to do:

$group_wages_array[6];

And

$thegroup['group_id'] = 6;

You can substitute this in as the key.

if (array_key_exists($thegroup['group_id'], $group_wages_array)) {
    $this_wages = $group_wages_array[$thegroup['group_id']];   
}
2
  • OK great, it worked when I used double brackets $this_wages = $combined_group_wages[$thegroup['group_id']]; Commented Oct 12, 2011 at 21:44
  • You are correct, that was a syntax error, it should be correct now. Thanks for pointing that out. Commented Oct 12, 2011 at 21:46

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.