I want create arrays with object keys in PHP, i.e. something like this:
<?php
$keyObject = new KeyObject;
$valueObject = new ValueObject;
$hash = array($keyObject => $valueObject);
However, this raises an error. Arrays may only have integer or string keys. I end up having to do something like:
$hash = array(
'key' => $keyObject,
'value' => $valueObject);
This works but it's not as neat as I'd like. Is there a better way? (Perhaps something from the SPL that I'm missing...)
TIA
Syntax for indexed arrays: array(value1, value2, value3, etc.) Syntax for associative arrays: array(key=>value,key=>value,key=>value,etc.)
No. Arrays can only have integers and strings as keys.
To create an array, you use the array() construct: $myArray = array( values ); To create an indexed array, just list the array values inside the parentheses, separated by commas.
We can use the array() function to create an array of objects in PHP. The function will take the object as the arguments and will create an array of those objects. We can create objects by creating a class and defining some properties of the class. The properties of the class will have some values.
You can use SplObjectStorage
from the SPL as a map with object keys:
$map = new SplObjectStorage;
$key = new StdClass;
$value = new StdClass;
$map[$key] = $value;
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