NYCPHP Meetup

NYPHP.org

[nycphp-talk] Best way to copy array by value

Chris Merlo chris at theyellowbox.com
Sun Feb 25 16:47:59 EST 2007


On 2/25/07, Aaron Fischer <agfische at email.smith.edu> wrote:
>
> I need to copy an array by value, not by reference.  Is there a best
> way to do this?
>

That depends on what the array contains.  If it contains primitives
(numbers, chars, or booleans), you can just write a loop.  If it contains
objects, just a loop still uses the = operator, which performs a deep copy
at the array level, but a shallow copy at the element/object level.  I teach
my (Java) students that they should have a deep copy method written in
classes they write (by overriding Object.clone), and then they can call that
in the loop.  But I'm not sure if there's an analogue to that method in PHP.

So, if you're copying an array of objects of a class you wrote, write in a
clone method.  If it's objects of a provided class, maybe the docs (or
others here) can shed some light on a clone-like method.  And if it's
primitives, just go for it.

BTW, just so you know, I haven't tested any of this.  This is just based on
my observation that PHP 5 is a whole lot like Java.  YMMV.
-c
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20070225/c850b832/attachment.html>


More information about the talk mailing list