For example:
$product = new Product("cat"); if(isset($sales[$product])){ $sales[$product]++; } else{ $sales[$product] = 1; }
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.
No. Arrays can only have integers and strings as keys.
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.
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.
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;
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.
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