Why php array allows different datatype to reside in an array as array should contains data of same datatype but that is not the case with php?
For example: - We can add ints, strings, floats, all of these in a single array.
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.
Related
In php you can create a matrix like $mat1 = array(); without knowing the size of the array and add elements in non sequential index like first $mat1[1][3] = x then $mat1[2][0] = y and so on. How can this be implemented in C++?
Also same thing for a 1D array?
What you have in PHP is an associative array; it's called std::map<> in C++. If you want an int -> int -> string map, you need:
std::map< int, std::map< int, std::string > > mat1;
Note that this does not preserve the order which the keys are inserted.
If you don't know the number of dimensions in advance, you might create a recursive data structure where each value is either of a value_type or a map.
From the PHP manual
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.
So check here : http://www.cplusplus.com/reference/map/map/
and : how to use stl::map as two dimension array
I have an array that I am trying to merge. The merging is dependent upon the key, the parent keys and the depth of the array. I can manipulate the array in a number of ways to achieve unique key values. The outcome is technically a binary search tree. I have attached two files json_in.txt is what I currently have and json_out.txt is what I want. You will notice that the json_in file has some unique key names in order to merge and the json_out file just has "name" and "children" keys. My plan was to use preg_replace_all to remove the digits from the json string after the array was merged, but if you know a better way then great!
Again, I am trying to make the json array in json_in.txt into json_out.txt and I can manipulate the key of json_in to whatever is needed in order to accomplish this.
json_in.txt
json_out.txt
I am using symfony and doctrine as my ORM.
For available types I have:
array
simple_array
json_array
I am wondering what the difference is between each of them: when do I use one or the other?
Can I have a demonstration for each of them to illustrate the differences?
I already use simple_array in some applications but I find I don't understand formType... (Or maybe I'm not using it well!? )
To illustrate my question, here is an example:
I have an Task that I have to run on specific days
So I created TaskEntity with days attribute
Days would be:
$days = array(
1=>true,
2=>true,
3=>true,
4=>true,
5=>true,
6=>false,
7=>false
);
But I have no idea which of the above types to choose ...
For your problem simple_array is the right way, the right way may also create seven boolean fields.
However here's a little vademecum:
The best way to see how a type works in doctrine is to read the code of the type, this is because there are several details that are taken for granted or are not really explained in the documentation.
So you can go into
/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Type.php
find your type and check if its methods work as you want.
Here some details:
simple_array
in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/SimpleArrayType.php
return implode(',', $value);
it's just a implode()/explode() of items, stores only the values and it's useful because you can easily query the database.
array
in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ArrayType.php
return serialize($value);
calls PHP to serialize()/unserialize(), it's faster than json_array. Looking at the code I think it also works with objects. Obviously if you see the field as plain text it's uncomprensible.
json_array
in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/JsonArrayType.php
return json_encode($value);
it calls json_encode()/json_decode(), if you look in the field you can see a unformatted JSON array but it's more readable than PHP's serialized object and is really more portable (JSON exists everywhere).
June 2018 update
now there is a complete and more updated documentation here
json_array is deprecated in favor of json type, it will leverage on new database features for json fields
Another consideration: The most efficient way to represent a small set of true/false values like the ones presented here would be a bitfield.
That way you're only storing one integer instead of a full string. And you avoid the encode/decode overhead.
See https://stackoverflow.com/a/5412214/827254 for a good example.
The best solution for your problem, as stated, would be to use an array mapping of type array or json_array but not simple_array. The reason is that the serialization method of simple_array is just a call to implode(',', $array) and that would retain only the values and not the keys of the array, thus invalid for your situation where you have an associative array.
However, you could also model your $days attribute as a 0-based array (i.e. monday would be zero, tuesday would be 1, etc.). In that case, it would work because the deserializing with explode(',', $serialized); generates a 0-based array with the serialised values.
According to the Documentation:
Doctrine ORM > Basic Mapping > Doctrine Mapping Types
You have 3 choices regaring array data:
array Type that maps a SQL CLOB to a PHP array using serialize() and unserialize().
simple_array Type that maps a SQL CLOB to a PHP array using implode() and explode(), with a comma as delimiter.
IMPORTANT: Only use this type if you are sure that your values cannot contain a ,.
json_array Type that maps a SQL CLOB to a PHP array using json_encode() and json_decode().
So, if you are sure about not having , (comma) in your array values, use simple_array. If you have a simple array structure (linear), use array and if you have more complex key-value arrays, use json_array.
From www.doctrine-project.org reference
Array types
Types that map array data in different variations such as simple arrays, real arrays or JSON format arrays.
array
Maps and converts array data based on PHP serialization. If you need to store an exact representation of your array data, you should consider using this type as it uses serialization to represent an exact copy of your array as string in the database. Values retrieved from the database are always converted to PHP's array type using deserialization or null if no data is present.
simple_array
Maps and converts array data based on PHP comma delimited imploding and exploding. If you know that the data to be stored always is a scalar value based one-dimensional array, you should consider using this type as it uses simple PHP imploding and exploding techniques to serialize and deserialize your data. Values retrieved from the database are always converted to PHP's array type using comma delimited explode() or null if no data is present.
json
Maps and converts array data based on PHP's JSON encoding functions. If you know that the data to be stored always is in a valid UTF-8 encoded JSON format string, you should consider using this type. Values retrieved from the database are always converted to PHP's native types using PHP's json_decode() function. JSON objects are always converted to PHP associative arrays.
an other page with good description
Recently I have read about hash-tables in a very famous book "Introduction to Algorithms". I haven't used them in any real applications yet, but want to. But I don't know how to start.
Can anyone give me some samples of using it, for example, how to realize a dictionary application (like ABBYY Lingvo) using hash-tables?
And finally I would like to know what is the difference between hash-tables and associative arrays in PHP, I mean which technology should I use and in which situations?
If I am wrong (I beg pardon) please correct me, because actually I am starting with hash-tables and I have just basic (theoretical) knowledge about them.
Thanks a lot.
In PHP, associative arrays are implemented as hashtables, with a bit of extra functionality.
However technically speaking, an associative array is not identical to a hashtable - it's simply implemented in part with a hashtable behind the scenes. Because most of its implementation is a hashtable, it can do everything a hashtable can - but it can do more, too.
For example, you can loop through an associative array using a for loop, which you can't do with a hashtable.
So while they're similar, an associative array can actually do a superset of what a hashtable can do - so they're not exactly the same thing. Think of it as hashtables plus extra functionality.
Code examples:
Using an associative array as a hashtable:
$favoriteColor = array();
$favoriteColor['bob']='blue';
$favoriteColor['Peter']='red';
$favoriteColor['Sally']='pink';
echo 'bob likes: '.$favoriteColor['bob']."\n";
echo 'Sally likes: '.$favoriteColor['Sally']."\n";
//output: bob likes blue
// Sally likes pink
Looping through an associative array:
$idTable=array();
$idTable['Tyler']=1;
$idTable['Bill']=20;
$idTable['Marc']=4;
//up until here, we're using the array as a hashtable.
//now we loop through the array - you can't do this with a hashtable:
foreach($idTable as $person=>$id)
echo 'id: '.$id.' | person: '.$person."\n";
//output: id: 1 | person: Tyler
// id: 20 | person: Bill
// id: 4 | person: Marc
Note especially how in the second example, the order of each element is maintained (Tyler, Bill Marc) based on the order in which they were entered into the array. This is a major difference between associative arrays and hashtables. A hashtable maintains no connection between the items it holds, whereas a PHP associative array does (you can even sort a PHP associative array).
php arrays ARE basically hash tables
The difference between an associative array and a hash table is that an associative array is a data type, while a hash table is a data implementation. Obviously the associative array type is very important in many current programming languages: Perl, Python, PHP, etc. A hash table is the main way to implement an associative array, but not quite the only way. And associative arrays are the main use of hash tables, but not quite the only use. So it's not that they are the same, but if you already have associative arrays, then you usually shouldn't worry about the difference.
For performance reasons, it can be important to know that your associative arrays in your favorite language are implemented as hashes. And it can be important to have some idea of the overhead cost of that implementation. Hash tables are slower and use more memory than linear arrays as you see them in C.
Perl lumps the two concepts together by calling associative arrays "hashes". Like a number of features of Perl, it isn't quite wrong, but it's sloppy.
An array in PHP is actually an ordered map, not hashtable. Main difference between map and hashtable consists in inability to remember the order in wich elements have been added. On the other hand, hashtables are much faster than maps. Complexity of fetching an element from map is O(nlogn) and from hashtable is O(1).
An associative array is an array where you don't access elements by an index, but by a key. How this works internally is implementation specific (there is no rule how it must work). An associative array could be implemented by a hash table (most implementations will do that), but it could also be implemented by some sort of tree structure or a skip list or the algorithm just iterates over all elements in the array and looks for a key that matches (this would be awfully slow, but it works).
A hash table is a way how to store data where values are associated to keys and where you intend to find values for keys within a (usually almost) constant time. This sounds exactly like what you expect of an associative array, that's why most of the time hash tables are used for implementing those arrays, but that is not mandatory.
Can you say that associative arrays in PHP are like 2D arrays?
No, they are still one-dimensional just like regular 0-based arrays. The difference is that you aren't limited to integers for the keys; you can use any arbitrary string.
And strictly speaking there isn't a technical distinction between associative and non-associative arrays. They use the same syntax, it's just your choice whether you use integers or strings or both for the keys.
A 2D array is more like a matrix, a plane, a coordinate system. An associative array on the other hand could be called a dictionary or hash.
$var[$x] = 1-dimensional
$var[$y][$y2] = 2-dimensional
$var[$z][$z2][$z3] = 3-dimensional
It doesn't matter if $x, $y or $z are numeric or strings, actually.
From wikipedia
Associative array
An associative array (also associative
container, map, mapping, dictionary,
finite map, and in query-processing an
index or index file) is an abstract
data type composed of a collection of
unique keys and a collection of
values, where each key is associated
with one value (or set of values).
So an associative array is actually an ADT, implemented in another way.
Instead, a 2d array "really" has two dimensions and is, usually, a primitive type.