Home » Php » php – Can I use an instantiated Object as an Array Key?

php – Can I use an instantiated Object as an Array Key?

Posted by: admin April 23, 2020 Leave a comment

Questions:

For example:

$product = new Product("cat");

if(isset($sales[$product])){
     $sales[$product]++;
}
else{
     $sales[$product] = 1;
}
How to&Answers:

From the docs:

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

You could give each instance a unique ID or override __toString() such that it returns something unique and do e.g.

$array[(string) $instance] = 42;

Answer:

You can use http://www.php.net/manual/en/class.splobjectstorage.php

$product = new Product("cat");
$sales = new SplObjectStorage();
if(isset($sales[$product])){
     $sales[$product]++;
}
else{
     $sales[$product] = 1;
}

It’s not a real array, but has a decent amount of array-like functionality and syntax. However, due to it being an object, it behaves like a misfit in php due to its odd foreach behavior, and its incompatibility with all the native php array functions. Sometimes you’ll find it useful to convert it to a real array via

$arr = iterator_to_array($sales);

so it plays nice with the rest of your codebase.

Answer:

There is a spl_object_hash function for getting unique object id as string, which can be used as array key. http://php.net/manual/en/function.spl-object-hash.php

Answer:

Only integers and strings are allowed as array keys. You could write a class that implements ArrayAccess if you absolutely need that functionality.

Answer:

If the object is a simple predefined classes made with new stdClass() it may be valid option to use the json representation of this class with json_encode.

$product = new stdClass();
$product->brand = "Acme";
$product->name = "Patator 3.14";

$product_key = json_encode($product);

if(isset($sales[$product_key])){
     $sales[$product_key]++;
}
else{
    $sales[$product_key] = 1;
}

But keep in mind that the equality of two objects is always a business model choice and must be carefully designed.

Answer:

You could have two arrays:

Array 1 contains the keys:   |  Array 2 contains the values
+--------+-------------+     |  +--------+------------+
| index: | value:      |     |  | index: | value:     |
| 0      | Object(key) |     |  | 0      | sth(value) |
| 1      | Object(key) |     |  | 1      | sth(value) |
+--------+-------------+     |  +--------+------------+

You search for the Object in array 1,
then you pick the index of that Object
use it as index for array 2 and
=> get the value

in php code

public function getValue($ObjectIndexOfYourArray){
  foreach(array1 as $key => $value) {
    if($value == ObjectIndexOfYourArray){
      return array2[$key];
    }
  }
}

I hope it helps