Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an instantiated Object as an Array Key?

Tags:

arrays

object

php

For example:

$product = new Product("cat");  if(isset($sales[$product])){      $sales[$product]++; } else{      $sales[$product] = 1; } 
like image 426
Tylo Avatar asked Jan 10 '11 01:01

Tylo


People also ask

Can JavaScript object keys be arrays?

Object. keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.

Can a key be an array?

No. Arrays can only have integers and strings as keys.

How do you assign an array to an object key?

To convert an array's values to object keys:Declare a new variable and set it to an empty object. Use the forEach() method to iterate over the array. On each iteration, assign the array's element as a key in the object.

How do you access keys in an array of objects?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


2 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; 
like image 59
Felix Kling Avatar answered Oct 05 '22 17:10

Felix Kling


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.

like image 20
goat Avatar answered Oct 05 '22 16:10

goat