6

I have 2 arrays.

$result = array();
$row = array();

Row's elements are all references and is constantly changing. For each iteration of $row I want to copy the values of row into an entry of $result and not the references.

I have found a few solutions but they all seem rather awful.

$result[] = unserialize(serialize($row));
$result[] = array_flip(array_flip($row));

Both of the above work but seem like a lot of unnecessary and ugly code just to copy the contents of an array of references by value, instead of copying the references themselves.

Is there a cleaner way to accomplish this? If not what would the most efficient way be?

Thanks.

EDIT: As suggested below something such as:

function dereference($ref) {
    $dref = array();

    foreach ($ref as $key => $value) {
        $dref[$key] = $value;
    }

    return $dref;
}

$result[] = dereference($row);

Also works but seems equally as ugly.

anomareh
  • 5,294
  • 4
  • 25
  • 22

3 Answers3

4

Not sure I totally understand the question, but can you use recursion?

function array_copy($source) {
    $arr = array();

    foreach ($source as $element) {
        if (is_array($element)) {
            $arr[] = array_copy($element);
        } else {
            $arr[] = $element;
        }
    }

    return $arr;
}

$result = array();
$row = array(
    array('a', 'b', 'c'),
    array('d', 'e', 'f')
);

$result[] = array_copy($row);

$row[0][1] = 'x';

var_dump($result);
var_dump($row);
Ross Snyder
  • 1,945
  • 11
  • 11
2

Extending the function above like follows solved a problem I had:

function array_copy($source) {
    $arr = array();

    foreach ($source as $element) {
        if (is_array($element)) {
            $arr[] = array_copy($element);
        } elseif (is_object($element)) {
            // make an object copy
            $arr[] = clone $element;
        } else {
            $arr[] = $element;
        }
    }
    return $arr;
}
Oliver
  • 21
  • 1
-1
$result = array_map(function($_){return $_;}, $row);
Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
  • 2
    Hello DonJaime, welcome to StackOverflow. :-) You seem to have posted a nice answer here. Yet, instead of just posting code as an answer, please add an explanation to your solution, so the readers can also understand why it works. – Philipp Maurer Apr 30 '20 at 13:05
  • How is this different from `$result = $row`? – Nico Haase Apr 30 '20 at 15:40