tags:

views:

41

answers:

3

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
+4  A: 

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);
}
meagar
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
@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.
meagar
+2  A: 

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.

Piskvor
A: 

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

tehsis
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()`
Piskvor