129

For example:

$names = {[bob:27, billy:43, sam:76]};

and then be able to reference it like this:

 $names[bob]
dreftymac
  • 31,404
  • 26
  • 119
  • 182
bzupnick
  • 2,646
  • 4
  • 25
  • 34

5 Answers5

156

http://php.net/manual/en/language.types.array.php

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Standard arrays can be used that way.

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
Jacob
  • 41,721
  • 6
  • 79
  • 81
33

There are no dictionaries in php, but PHP array's can behave similarly to dictionaries in other languages because they have both an index and a key (in contrast to Dictionaries in other languages, which only have keys and no index).

What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array in PHP, but there is no way to do an equivalent operation using a dictionary in a language like Python(which has both arrays and dictionaries).

print $array[0]

PHP arrays also give you the ability to print a value by providing the value to the array

print $array["foo"]
Sam
  • 1,765
  • 11
  • 82
  • 176
Brént Russęll
  • 756
  • 6
  • 17
7

Normal array can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.

$names = [
    'bob' => 27,
    'billy' => 43,
    'sam' => 76,
];

$names['bob'];

And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject or you can use SplObjectStorage class which is map (dictionary) implementation allowing objects to be assigned as keys.

Jsowa
  • 9,104
  • 5
  • 56
  • 60
0

Use arrays:

<?php

$arr = [
    "key" => "value",
    "key2" => "value2"
];
Mateja
  • 271
  • 1
  • 11
0

If you intend to use arbitrary objects as keys, you may run into "Illegal offset type". To resolve this you can wrap the key with the call of spl_object_hash function, which takes any object, and returns its unique hash.

One thing to keep in mind, however, is that then the key itself will be the hash, and thus you will not be able to get a list of the objects used to generate those hashes from your dictionary. This may or may not be what you want in the particular implementation.

A quick example:

<?php

class Foo
{
}

$dic = [];

$a = new Foo();
$b = new Foo();
$c = $a;

$dic[spl_object_hash($a)] = 'a';
$dic[spl_object_hash($b)] = 'b';
$dic[spl_object_hash($c)] = 'c';

foreach($dic as $key => $val)
{
    echo "{$key} -> {$val}\n";
}

The output i get is:

0000000024e27223000000005bf76e8a -> c
0000000024e27220000000005bf76e8a -> b

Your hashes, and hashes at different executions may be different.

v010dya
  • 5,296
  • 7
  • 28
  • 48