views:

1706

answers:

2

Is it possible to remove an array element by a pointer?

Multidimensional array:

$list = array(
    1=>array(
          2=>array('entry 1'),
          3=>array('entry 2')
    ),
    4=>'entry 3',
    5=>array(
          6=>array('entry 4')
    )
);

Reference array:

$refs = array(
     1=>&$list[1], 
     2=>&$list[1][2],
     3=>&$list[1][3],
     4=>&$list[4],
     5=>&$list[5],
     6=>&$list[5][6]
);

The reference array contains only pointer (alias) to the multidimensional array elements. Now I want to delete (unlink) the elements from the $list array.

By using

    $n=3;
    unset($refs[$n])
but PHP only deletes the pointer.

Thanks for any help.

+4  A: 

Your reference array seems to be wrong:

$refs = array(
     1 => &$list[1],
     2 => &$list[2],
     3 => &$list[3],
     4 => &$list[4],
     5 => &$list[5],
     6 => &$list[6]
);

But your $list array does not contain elements 2, 3 and 6. So the $refs array should rather look like:

$refs = array(
     1 => &$list[1],
     2 => &$list[1][2],
     3 => &$list[1][3],
     4 => &$list[4],
     5 => &$list[5],
     6 => &$list[5][6]
);

Depending on what your requirements are you could do:

$refs[2] = null;
unset($refs[2]);

But this will leave $list[1][2] as an array element containing NULL.

EDIT:

To remove the element from it's source array $list you have to resort to some recursive search function (untested - may need some tweaking):

function removeElement($element, array &$array)
{
    foreach ($array as $key => &$value) {
        if ($element == $value) {
            unset($array[$key]);
            return true;
        } else if (is_array($value)) {
            $found = removeElement($element, $value);
            if ($found) {
                return true;
            }
        }
    }
    return false;
}

removeElement($refs[2], $list);
Stefan Gehrig
Thanks I fixed the $refs array. I need to get rid of the element in the $list array.
A: 

Would it be possible to store a reference to the "parent" element and the index, like

<?php
$list = array(
  1=>array(
    2=>array('entry 1'),
    3=>array(
      4=>'entry 2',
      5=>'entry 3'
    )
  ),
  2=>'entry 3',
  5=>array(
    'foo'=>'entry 4',
    1=>'entry 99'
  )
);

// delete
$refs = array(
  // 'entry 2'
  array(&$list[1][3], 4),
  // and 'entry 4'
  array(&$list[5], 'foo')
);

foreach($refs as $r) {
    unset($r[0][$r[1]]);
}
print_r($list);
VolkerK