Reputation: 308
I need to remove an object from an array in php but I need the object reference to still exist, when I tried using unset()
as described here it unset both the array element and the object itself, how can I remove the reference from the array without destroying the object?
my code looks like the following:
$this->array[id] = myobject;
unset($this->array[$id]);
Upvotes: 1
Views: 2369
Reputation: 31
Have you tried to keep a reference of the object before destroy array reference?
$user = new User('name','surname');
$myUserReference = $user;
$data = array('user'=> $user);
print_r($data);
unset($data['user']);
print_r($data);
This should print an array containing $user object and an empty array then. You should have a reference to $user object in $myUserReference var
Upvotes: 1
Reputation: 238
This code works just fine for me:
$my_var = 1;
$my_array = array();
$id = 0;
$my_array[$id] = $my_var;
print_r($my_array);
print_r($my_var);
unset($my_array[$id]);
print_r($my_array);
print_r($my_var);
At the end of it all, I have cleared the $id
(0) index from $my_array
, by $my_var
is still equal to 1
.
Upvotes: 2
Reputation: 23729
You need another reference for this object. Look at this code:
<?php
$var = 1;
$data = array("id" => &$var);
unset($data['id']);
var_dump($var);
var_dump($data);
It prints:
int(1)
array(0) {
}
Just keep another reference to this object somewhere else.
Upvotes: 1