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 ?
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.
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).
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().
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With