appareil
appareil

Reputation: 23

Having an array with references to itself in PHP

I want to achieve this in php - but is it possible and if so, how?

An Array of two elements, the first is an Array of nested arrays (contents and depth is unknown, you only know that each Array has an id) and the second is an Array of references to every Array in the first element. Something like this:

$all = Array (
  'nested_arrays' => Array(
    'id0' => Array(
      'id8' => Array(
        ...
      )...
    )...
  'references' => Array(
    'id0' => (reference to Array id0),
    'id8' => (reference to Array id8),
    ...
  )
)

Then you could access every Array without knowing where it is, like

$all['references']['id8']

and you could even do

unset($all['references']['id8'])

...yes, or could you?

Upvotes: 2

Views: 62

Answers (2)

Vitali Protosovitski
Vitali Protosovitski

Reputation: 563

I'd rather create an object that implements iterator interface. Object by it's nature is passed by reference.

$id0 = new MyIterator($array);
$all = [
  'nested_arrays' => [
    'id0' => $id0
  ],
  'references' => [
    'id0' => $id0
  ]
];

Alternative way is to iterate recursively the 'nested_array' and fill the 'references' array

foreach ($nested as $k => $v) {
  // Custom recursive iteration
  ...
  $all['references'][$k] = &$v;
}

And in general you can not delete the original value nor the object by unsetting it's reference. The original value gets destroyed only when all pointers to this value are unset. You will have to loop through the array.

Upvotes: 0

Random Dude
Random Dude

Reputation: 883

You can do the first one by storing references in the array's references, like this:

$all = [
    'nested_arrays' => [
        'id0' => [
            'id8' => [
                'hello'
            ],
            'id3' => [
                'id6' => 'apple'
            ]
        ]
    ],
];

$all['references']['id0'] = &$all['nested_arrays']['id0'];
$all['references']['id8'] = &$all['nested_arrays']['id0']['id8'];
$all['references']['id6'] = &$all['nested_arrays']['id0']['id3']['id6'];

Then checking the outputs:

echo '<pre>'. print_r($all['references']['id8'], true) . '</pre>';
echo '<pre>'. print_r($all['references']['id6'], true) . '</pre>';

outputs:

Array
(
    [0] => hello
)

apple

However you can't use unset on this, because that would remove the element of the array only, not the array element where it points to.

Upvotes: 1

Related Questions