Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP dereference array elements

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.

like image 443
anomareh Avatar asked Mar 02 '10 00:03

anomareh


People also ask

What is array Dereferencing in PHP?

Array Dereferencing is really very good feature added in PHP 5.4. With this you can directly access an array object directly of a method a functions. Now we can say that no more temporary variables in php now.

Are there pointers in PHP?

PHP does not have pointers, but it does have references. The syntax that you're quoting is basically the same as accessing a member from a pointer to a class in C++ (whereas dot notation is used when it isn't a pointer.)

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.


2 Answers

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);
like image 194
Ross Snyder Avatar answered Oct 17 '22 06:10

Ross Snyder


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;
}
like image 29
Oliver Avatar answered Oct 17 '22 07:10

Oliver