Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there dictionaries in php?

For example:

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

and then be able to reference it like this:

 $names[bob]
like image 517
bzupnick Avatar asked Jun 27 '11 08:06

bzupnick


People also ask

What are arrays in PHP?

Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.

How many types of array are available in PHP?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

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.


3 Answers

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.

like image 141
Jacob Avatar answered Oct 01 '22 18:10

Jacob


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"]
like image 29
Brént Russęll Avatar answered Oct 01 '22 20:10

Brént Russęll


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.

like image 40
Jsowa Avatar answered Oct 01 '22 20:10

Jsowa