Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can use the fact that functions dereferences results when returning, for exemple here <code>$array_by_myclone</code> will still have a reference to <code>$original</code> (<code>$array_by_myclone[0][0] == 'foo'</code>) while <code>$array_by_assignment</code> will have a cloned value (<code>$array_by_assignment[0][0] == 'bar'</code>)</p> <pre><code>$original = 'foo'; $array_of_reference = array(&amp;$original); function myclone($value) { return $value; } $array_by_myclone = array(); $array_by_myclone[] = array_map('myclone', $array_of_reference); $array_by_assignment = array(); $array_by_assignment[] = $array_of_reference; $original = 'bar'; var_dump($array_by_myclone[0][0]); // foo, values were cloned var_dump($array_by_assignment[0][0]); // bar, still a reference </code></pre> <p>EDIT: I wanted to check if the comment saying <code>unserialize(serialize())</code> was faster was right so I did the test using php 5.5, and it turns out this is wrong: using the serialization method is slower even with a small dataset, and the more data you have the slower it gets.</p> <pre><code>lepidosteus@server:~$ php -v PHP 5.5.1-1~dotdeb.1 (cli) (built: Aug 3 2013 22:19:30) Copyright (c) 1997-2013 The PHP Group Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies with Zend OPcache v7.0.2-dev, Copyright (c) 1999-2013, by Zend Technologies lepidosteus@server:~$ php reference.php 1 myclone: 0.000010 seconds serialize: 0.000012 seconds lepidosteus@server:~$ php reference.php 1000000 myclone: 0.398540 seconds serialize: 0.706631 seconds </code></pre> <p>Code used:</p> <pre><code>&lt;?php $iterations = 1000000; if (isset($argv[1]) &amp;&amp; is_numeric($argv[1])) { $iterations = max(1, (int)$argv[1]); } $items = array(); for ($i = 0; $i &lt; $iterations; $i++) { $items[] = 'item number '.$i; } $array_of_refs = array(); foreach ($items as $k =&gt; $v) { $array_of_refs[] = &amp;$items[$k]; } function myclone($value) { return $value; } $start = microtime(true); $copy = array_map('myclone', $array_of_refs); $time = microtime(true) - $start; printf("%-10s %2.6f seconds\n", 'myclone:', $time); $start = microtime(true); $copy = unserialize(serialize($array_of_refs)); $time = microtime(true) - $start; printf("%-10s %2.6f seconds\n", 'serialize:', $time); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload