Keith
Keith

Reputation: 1185

php array parent array position

Is there a way to get the the current position of an array from within a nested array ?

I have a php script that has a for loop which cycles through an array, with in this is an nested loop which cycle through a sub array. I can use pos() to get the position of the child array, is there anyway of getting the current position of the parent array.

I am sure there must be a way to do this, or is the best way to just create a counter?

thanks in advance

.k

Upvotes: 0

Views: 1094

Answers (2)

johannes
johannes

Reputation: 15969

A PHP variable has no information from where it is referenced - due to references and copy-on-write there might be even more things (global/local variables, array elements, properties, ...) pointing to a single variables.

If you have a reference to the "parent" element you can use pos() on that, if not you have to handle this yourself.

Upvotes: 0

Scott Saunders
Scott Saunders

Reputation: 30394

If you're using a for loop, you already have a counter. In this example, it's $i :

for($i = 0; $i < $arrayLength; $i++) ...

If you're actually using a foreach loop, use the syntax that gives you the key:

foreach($array as $key => $value) ...

Upvotes: 3

Related Questions