3

I'm trying to find the index based on the value stored within it.

This would normally be easy, but the array I'm working with is highly nested. Each index 0,1,2 has fields f1,f2,f3 . I'm trying to find which index 0,1,2 has in its f2 field the value this stored in it. In this case, it's index 0. So that's the output I'm looking for. Is there a neat trick in PHP to do this effectively?

$somearray[0][f1] = "not this";
$somearray[0][f2] = "this"; 
$somearray[0][f3] = "not this"; 

$somearray[1][f1] = "not this";
$somearray[1][f2] = "not this";
$somearray[1][f3] = "not this"; 

$somearray[2][f1] = "not this"; 
$somearray[2][f2] = "not this"; 
$somearray[2][f3] = "not this"; 

1 Answer 1

3

In this case, it's index 0. So that's the output I'm looking for.

$somearray[0]['f1'] = "not this";
$somearray[0]['f2'] = "this";
$somearray[0]['f3'] = "not this";

$somearray[1]['f1'] = "not this";
$somearray[1]['f2'] = "not this";
$somearray[1]['f3'] = "not this";

$somearray[2]['f1'] = "not this";
$somearray[2]['f2'] = "not this";
$somearray[2]['f3'] = "not this";

foreach($somearray as $key => $value)
{
  if($value['f2'] === 'this')
  {
     echo $key; // find out the key
  }
}

Output:

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

1 Comment

Thank you. Does what I was trying to do.

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.