0

I'm wondering if the elements of array can 'know' where they are inside of an array and reference that:

Something like...

$foo = array(
   'This is position ' . $this->position,
   'This is position ' . $this->position,
   'This is position ' . $this->position,
),

foreach($foo as $item) {

  echo $item . '\n';
}

//Results:
// This is position 0
// This is position 1
// This is position 2
0

3 Answers 3

4

They can't "reference themselves" per se, and certainly not via a $this->position as array elements are not necessarily objects. However, you should be tracking their position as a side-effect of iterating through the array:

// Sequential numeric keys:
for ($i = 0; $i < count($array); ++$i) { ... }

// Non-numeric or non-sequential keys:
foreach (array_keys($array) as $key) { ... }
foreach ($array as $key => $value) { ... }

// Slow and memory-intensive way (don't do this)
foreach ($array as $item) {
  $position = array_search($item, $array);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I knew this was possible, but I was wondering if there was a way to do it without a foreach statement. I guess it isn't.
@DKinzer You can use array_search to find the index of an item in an array given only an array and one of its elements, but it's hard to arrive at that state without also having the index already handy.
2

No, PHP's arrays are plain data structures (not objects), without this kind of functionality.

You could track where in the array you are by using each() and keeping track of the keys, but the structure itself can't do it.

Comments

0

As you can see here: http://php.net/manual/en/control-structures.foreach.php

You can do:

foreach($foo as $key => $value) {
  echo $key . '\n';
}

So you can acces the key via $key in that example

1 Comment

You can access it that way, once you've defined the array; but I believe the OP was asking about something like SQL's LAST_INSERT_ID()

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.