Sorry to ask, its late and I can't figure a way to do it... anyone can help?
$users = array(
array(
"name" => "John",
"age" => "20"
),
array(
"name" => "Betty",
"age" => "22"
)
);
$room = array(
"furniture" => array("table","bed","chair"),
"objects" => array("tv","radio","book","lamp"),
"users" => &$users
);
var_dump $room shows:
...
'users' => &
...
Which means "users" is a reference.
I would like to do something like this:
foreach($room as $key => $val) {
if(is_reference($val)) unset($room[$key]);
}
The main goal is to copy the array WITHOUT any references.
Is that possible?
Thank you.
The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.
In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value. It only contains an object identifier which allows using which the actual object is found.
Let's explain what is an object and associative array in PHP? An object is an instance of a class meaning that from one class you can create many objects. It is simply a specimen of a class and has memory allocated. While on the other hand an array which consists of string as an index is called associative array.
The is_object() function checks whether a variable is an object. This function returns true (1) if the variable is an object, otherwise it returns false/nothing.
You can test for references in a multi-dimensional array by making a copy of the array, and then altering and testing each entry in turn:
$roomCopy = $room;
foreach ($room as $key => $val) {
$roomCopy[$key]['_test'] = true;
if (isset($room[$key]['_test'])) {
// It's a reference
unset($room[$key]);
}
}
unset($roomCopy);
With your example data, $room['furniture']
and $roomCopy['furniture']
will be separate arrays (as $roomCopy
is a copy of $room
), so adding a new key to one won't affect the other. But, $room['users']
and $roomCopy['users']
will be references to the same $users
array (as it's the reference that's copied, not the array), so when we add a key to $roomCopy['users']
it is visible in $room['users']
.
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