For example:
$names = {[bob:27, billy:43, sam:76]};
and then be able to reference it like this:
$names[bob]
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.
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"]
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.
Use arrays:
<?php
$arr = [
"key" => "value",
"key2" => "value2"
];
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.
Related
I can define an array in PHP like this:
$array = array();
In C++, we have two kinds of array.
The first kind is a fixed size array, for example:
int arr[4]; // 4 ints, hardcoded size
The second kind is a dynamic sized array
std::vector<int> v; // can grow and shrink at runtime
What kind of array does PHP use? Are both kinds of arrays in PHP? If so, can you give me examples?
PHP is not as strict as C or C++. In PHP you don't need to specify the type of data to be placed in an array, you don't need to specify the array size either.
If you need to declare an array of integers in C++ you can do it like this:
int array[6];
This array is now bound to only contain integers. In PHP an array can contain just about everything:
$arr = array();
$arr[] = 1;
$arr[] = 2;
$arr[] = 3;
$arr[] = 4;
var_dump($arr); //Prints [1,2,3,4]
$arr[] = 'hello world'; //Adding a string. Completely valid code
$arr[] = 3.14; //Adding a float. This one is valid too
$arr[] = array(
'id' => 128,
'firstName' => 'John'
'lastName' => 'Doe'
); //Adding an associative array, also valid code
var_dump($arr); //prints [1,2,3,4,'hello world',3.14, [ id => 128, firstName => 'John', lastName => 'Doe']]
If you're coming from a C++ background it's best to view the PHP array as a generic vector that can store everything.
From php.net
An array in PHP is actually an ordered map. A map is a type that
associates values to keys. This type is optimized for several
different uses; it can be treated as an array, list (vector), hash
table (an implementation of a map), dictionary, collection, stack,
queue, and probably more. As array values can be other arrays, trees
and multidimensional arrays are also possible.
Basically there are three Usage patterns of array in PHP.
Indexed array: Arrays with sequential numeric index, such as 0, 1, 2, etc. Example:
$myarray = array();
$myarray[0] = "test data 1";
$myarray[1] = "test data 2";
$myarray[3] = "test data 3";
Associative array: This is the most frequently used type of PHP arrays whose elements are defined in key/value pair. Example:
$myarray = array();
$myarray["key1"] = "value 1";
$myarray["key2"] = "value 2";
$myarray["key3"] = "value 3";
Multidimensional array: Arrays whose elements may contains one or more arrays. There is no limit in the level of dimensions. Example:
$myarray = array();
$myarray[0] = array("data01","data02","data03");
$myarray[1] = array("data11","data12","data13");
For more details - Refer to PHP 5 Arrays.
PHP uses three kinds of array:
Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.
Numeric Array Ex:
$numbers = array( 1, 2, 3, 4, 5);
Associative Array Ex:
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
Multidimensional Array Ex:
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
A php array, in C++ terms, is roughly:
std::map< std::experimental::any, std::experimental::any >
where std::experimental::any is a type that can hold basically anything. The php equivalent also can be sorted with the equivalent of <.
Well not quite -- closer to the truth is that a php array is an abstract interface that exposes much of the operations that the above map would provide in C++ (the C++ map is a concrete implementation).
Arrays with contiguous numeric keys stored in the Variant are treated much like a std::vector<Variant>, and under the interface the php system might even use vector<Variant> or something similar to store it, or even have two different internal details, one of which is for contiguous blocks of integer indexed data, and the other for sparse entries. (I don't know how php is implemented, but that is how I would do it)
PHP uses numeric, associative arrays, and multidimensional arrays. Arrays are dynamic in nature, and no size should be mentioned. Go through php.net/manual/en/language.types.array.php to find details.
I have several associative arrays in PHP that looks like this:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
I want to create another associative array, using the serialized values of the previous arrays are used as the array keys. For example:
$newArray = array("data1's serialized key" => "someNewValue", ... );
Are serialized arrays suitable for being used as array keys?
Do they contain any unacceptable characters?
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Are serialized arrays suitable for being used as array keys?
Yup! As far as I know you can use serialized arrays as a key in another array. But the I cannot think of any use-case for this. :P
Do they contain any unacceptable characters?
No, until and unless you specify any unacceptable characters in the original array.
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Nope.
So, you code would look like:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);
I am going to construct a highly complex associative array in php. But first, I need to initialize it.
What is the right way to initialize it? My initialization is as follows;
$ComplexAssociativeArray = [];
Are there better ways?
If you go for
$array = [
"foo" => "bar",
"bar" => "foo",
];
It wont work in php versions before 5.4
but below way work in all versions
$array = array(
"foo" => "bar",
"bar" => "foo",
);
I think that is the main difference.
Quoting from php docs for arrays
As of PHP 5.4 you can also use the short array syntax, which replaces
array() with [].
I would think this would be easier to find but I've been scouring google with no luck. Can you create an array with both a numbered and named index? I know it has to be possible because mysqli_fetch_array returns one, but I can't find any reference to it.
Thanks.
As per official documentation:
An array in PHP is actually an ordered map. A map is a type that associates values to keys.
The key can either be an integer or a string. The value can be of any type.
Nothing to it:
$x = array();
$x['foo'] = 'bar';
$x[1] = 'baz';
Use any key you want. As long as whatever you're using for a key is an int or a valid string, it can be a key.
Yes. PHP arrays can have mixed keys (strings and integers). A reference to it can be found in the docs here: http://php.net/manual/en/language.types.array.php.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Check Example #3:
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>
outputs:
array(4) {
["foo"] => string(3) "bar"
["bar"] => string(3) "foo"
[100] => int(-100)
[-100] => int(100)
}
It's pretty handy in JS to create objects like this:
test = { foo : { bar : "hello world" }, bar2 : "hello world 2" }
and then use them like:
test.foo.bar
test.bar2
Is there anything like this in PHP without declaring classes?
It's called associative arrays.
Example (note: the indentation is for layout purposes):
$test = array(
'foo' => array(
'bar' => 'hello world'
),
'bar2' => 'hello world 2'
);
$test['foo']['bar'];
$test['bar2'];
This is equivalent to the following Javascript code:
var test = {
'foo': {
'bar': 'hello world',
},
'bar2': 'hello world 2'
};
As an alternative, you can use the pre-declared StdClass.
$test = new StdClass;
$test->foo = new StdClass;
$test->foo->bar = 'hello world';
$test->bar2 = 'hello world 2';
which would be written in JavaScript as:
var test = new Object;
test.foo = new Object;
test.foo.bar = 'hello world';
test.bar2 = 'hello world 2';
(note: new Object is the same as {} in Javascript)
stdClass allows you to create (essentially) typeless objects. For example:
$object = (object) array(
'name' => 'Trevor',
'age' => 42
);
As shown here, the fastest way to create a stdClass object is to cast an associative array. For multiple levels, you just do the same thing again inside like this:
$object = (object) array(
'name' => 'Trevor',
'age' => '42',
'car' => (object) array(
'make' => 'Mini Cooper',
'model' => 'S',
'year' => 2010
)
);
Another method is to convert the associative array to an object afterwards with a recursive function. Here's an example.
function toObject(array $array) {
$array = (object) $array;
foreach ($array as &$value)
if (is_array($value))
$value = toObject($value);
return $array;
}
// usage:
$array = // some big hierarchical associative array...
$array = toObject($array);
This is useful when you're not the one making the associative array.
Unfortunately, even though PHP 5.3 supports anonymous methods, you cannot put an anonymous method into a stdClass (though you can put one into an associative array). But this isn't too bad anyway; if you want functionality in it, you really should create a class instead.
You can use a StdClass object or an ArrayObject which are included in php (though the latter requires that you have SPL installed). Though unless you need to access the values specifically with the -> operator its more efficient to just use an associative array instead.
I think what you are looking for is an Associative Array
$test["foo"]["bar"]
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=keyed+arrays
The closest thing would be arrays.
$test = array(
'foo' => array('bar' => 'hello world'),
'bar2' => 'hello world 2',
);
echo $test['foo']['bar'];
Technically, no. However if you are creating a data object (ie no methods), you could technically write a JSON string and use
$obj = json_decode($obj_string);
I wouldn't recommend it however. I assume there would be significant speed loss.
EDIT
Though it goes without mentioning, associative arrays should be used for this instead of flat data objects.
The only reason to do that is if you wish to pass data back to a JavaScript function with JSON. In that case, use json_encode on the array. Otherwise, just keep it as an array, as there's not reason to encode it and then decode it just so it looks like JavaScript.
Try this way: https://github.com/ptrofimov/jslikeobject
Author implemented JS-like objects, you can even access properties from functions via $this pointer.
But perhaps it is not so good to use such objects instead of usual ones.
$a = array(
'a'=> 123,
'b'=> 334,
'c'=> 7853
);
echo json_encode($a);
This will be the result: {"a":123,"b":334,"c":7853}