Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push a copy of an object into array in PHP

Tags:

arrays

php

I tried to add objects into array in PHP but it didn't work, tried 2 methods:

#1

$obj->var1 = 'string1';
$obj->var2 = 'string1';
$arr[] = $obj;
$obj->var1 = 'string2';
$obj->var2 = 'string2';
$arr[] = $obj;

#2

$obj->var1 = 'string1';
$obj->var2 = 'string1';
array_push($arr,$obj);
$obj->var1 = 'string2';
$obj->var2 = 'string2';
array_push($arr,$obj);

Both methods will add the latest object into entire array. Seems that object is added to the array by reference. Is there a way to add they into array by value ?

like image 910
chubbyk Avatar asked Apr 11 '11 17:04

chubbyk


People also ask

Can you push an object into an array?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you add an object to an array of objects in PHP?

Just do: $object = new stdClass(); $object->name = "My name"; $myArray[] = $object; You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

How do you push an element into a new array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().


1 Answers

Objects are always passed by reference in php 5 or later. If you want a copy, you can use the clone operator

$obj = new MyClass;
$arr[] = clone $obj;
like image 168
Decko Avatar answered Sep 30 '22 19:09

Decko