Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: check if object/array is a reference

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.

like image 431
lepe Avatar asked Jun 30 '10 09:06

lepe


People also ask

How do you check if an array is an object or array in PHP?

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.

Are PHP objects passed by reference?

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.

Is object an array PHP?

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.

How check variable is object or not in PHP?

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.


1 Answers

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'].

like image 77
Chris Avatar answered Sep 23 '22 19:09

Chris