Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create array-like data-structures with object keys in PHP?

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

like image 647
Carlton Gibson Avatar asked Jan 19 '10 09:01

Carlton Gibson


People also ask

How do you create an array with key value?

Syntax for indexed arrays: array(value1, value2, value3, etc.) Syntax for associative arrays: array(key=>value,key=>value,key=>value,etc.)

Can a key be an array PHP?

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

How do you create an array in PHP?

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.

Can you have an array of objects in PHP?

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.


1 Answers

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;
like image 159
Ben James Avatar answered Sep 22 '22 19:09

Ben James