PHP Markup Array Elements

I have 2 arrays.

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

Line items are links and are constantly changing. For each iteration of $row I want to copy the values lines in the $result entry, not links.

I found several solutions, but they all seem pretty terrible.

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

Both of these works, but seem like very unnecessary and ugly code to just copy the contents of an array of links by value, rather than copy the links themselves.

Is there a cleaner way to do this? If not for the most effective way?

Thanks.

EDIT: As shown below, for example:

 function dereference($ref) { $dref = array(); foreach ($ref as $key => $value) { $dref[$key] = $value; } return $dref; } $result[] = dereference($row); 

Also works, but seems just as ugly.

+6
arrays reference php dereference
source share
2 answers

Not sure if I fully 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); 
+4
source share

The extension of the function above, as follows, solved the 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; } 
+2
source share

All Articles