Search code examples
phparraysreferencetraversallevels

PHP: How to traverse an associative-array by having a child's reference?


I have a function declaration like this:

function func(&$array){//do something};

Then I have an array like this:

$people[gender][singlePerson][property]=>value

I call my function this way:

func($people[man][person1]);

In my function now I have the parameter $array that contain the reference to:

$people[man][person1]

Now the problem... How can i traverse the reference to get the position

$people[man]

In other word, having the reference $people[man][person1] how con i "level up" on the array?


Solution

  • If you pass $people['men']['person1'] to your function, there's no way how this function can know that this array has been nested within $people['men'] outside of it.

    how can i "level up" on the array?

    You can't. And what's more: You shouldn't need to.

    The only reasonable answer here is: change the design of code to meet your requirements, try different approach, consider passing additional parameters to this function etc.