david
david

Reputation: 33507

Is it possible in PHP for an array to reference itself within its array elements?

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

Upvotes: 0

Views: 384

Answers (3)

user229044
user229044

Reputation: 239240

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);
}

Upvotes: 4

tehsis
tehsis

Reputation: 1612

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

Upvotes: 0

Piskvor left the building
Piskvor left the building

Reputation: 92752

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.

Upvotes: 2

Related Questions