Are PHP Associative Arrays ordered? - php

I come from python background and the python datatype which is similar (a dictionary) is an unordered set of key value pairs.
I am wondering if PHP associative arrays are unordered? They appear to be ordered.
$test = array(
'test' => 'test',
'bar' => 'bar',
);
var_dump($test);
var_dump(array_slice($test, 0, 1));
Test always comes before bar and I can slice this array as you see. So is this always guaranteed to be ordered across php versions? Is the order just the order that I have declared the array with? So something is internally pointing 'test' to place [0] in the array? I have read http://php.net/manual/en/language.types.array.php but it doesn't shed too much light on this issue. I appreciate your responses. Ty

PHP associative arrays (as well as numeric arrays) are ordered, and PHP supplies various functions to deal with the array key ordering like ksort(), uksort(), and krsort()
Further, PHP allows you to declare arrays with numeric keys out of order:
$a = array(3 => 'three', 1 => 'one', 2 => 'two');
print_r($a);
Array
(
[3] => three
[1] => one
[2] => two
)
// Sort into numeric order
ksort($a);
print_r($a);
Array
(
[1] => one
[2] => two
[3] => three
)
From the documentation:
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.

The documentation states:
An array in PHP is actually an ordered map.
So yes, they are always ordered. Arrays are implemented as a hash table.

From the php manual:
Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information.
I have relied on the fact that they are ordered and it has worked consistently in every project I've had.

The array is ordered but that does not mean the keys are sorted, it means that they are in a given order. Where the precise order is not specified, but it appears to be the order in which you introduced the key-value pairs in it.
To understand it, think what would it mean to not be ordered?
Well think to a relation in a relational database.
A relation is not intrinsically ordered: when you access it with a query the database, unless you provide an order clause, can return the same data in any order.
Even if the data was not modified the same data can be returned in different order.

Related

PHP is ksort() necessary if using array values only individually?

A simple question today!
I've ended up defining the values in my array non-sequentially, in other words 2 => 'marmosets' is defined before 0 => cats and 1 => dogs. It is my understanding is that the keys will assign properly (ie value marmosets will indeed be key 2 not key 0 even though it is defined first), but that my array will be 'out of order' such that a print_r() would output:
2 => marmosets
0 => cats
1 => dogs
And that if I want to put them in numerical order by key, ksort() will do that job.
(a) Is my understanding correct?
(b) If I'm only using these values individually, and never need to output the list, is there any harm/impact in skipping the ksort() and leaving them "out of order"?
(a) Yes and (b) No.
a) PHP's arrays are ordered maps. The default order will stay insertion order until you change that, e.g. by sorting.
b) If you never do anything that relies on any order, e.g. just accessing data by keys, the order is irrelevant, so there's no harm.
Printing the array will indeed print it in the order your created it with, whether those keys are numeric or associative. This can be proven simply by testing your example. There is no harm in skipping ksort if you do not rely on the actual order of the array. However, it does not hurt to use ksort either. Unless you are dealing with huge amounts of data, sorting the array once in your application will have no noticable effect on performance.

2D array storage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Why it is the best practice to store your message or results in the two dimensional array?
I grilled it a lot in my mind but failed to produce an exact answer
The answers which came up to me with lot of grilling are as following :-
To store 2 messages at one time
To have the facility to store large messages
To store the large number of messages
though I am not sure about any one of them I admit it that my problem is not that programming oriented!
It might be best to look at what the PHP docs have to say about arrays first:
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.
As you can see from that definition, php arrays are very flexible and cover a lot of use cases. The particular area you are asking about is the multidimensional(2D) PHP array style. Now take a look at how a creating a 2D array looks:
$blank2DArray = array(array());
It's fairly clear that what you have is simply an array of arrays, ie a 2d Array.
So where 2D arrays are useful are cases where you have data that goes beyond simple key => value usage. A simple example: You have some results from multiple race car drivers and their scores from a race course. Each driver has multiple pieces of information so you need more than just a single key => value stored for each driver. You could make an object with attributes to store with this kind of thing, but you could handle it very quickly and simply with a PHP 2D array like this:
$drivers = array();
$drivers[0] = array('driver_id' => 2, 'course_id' => 5 'score' => 61.6);
$drivers[1] = array('driver_id' => 3, 'course_id' => 4 'score' => 70.8);
$drivers[2] = array('driver_id' => 8, 'course_id' => 2 'score' => 76.8, 'winner' => 1);
Each driver and their data are represented by a new array and each is added with an index(this does not need to be numeric). Notice driver[2] has an attribute winner that the others do not have; this is allowed because PHP allows for jagged arrays, ie not all entries have to be the same size. You can easily access child elements of each array like this:
$drivers[0]['driver_id'] //prints 2
$drivers[1]['course_id'] //prints 4
$drivers[2]['score'] //prints 76.8
PHP arrays are excellent for solving a variety of problems and 2D arrays specifically allow for representing complex data far beyond simple key => value storage. For an in-depth look under the hood at PHP arrays check out this blog post: Link
So to answer your question it may not always be best practice to use a 2D array, it will depend on the problem you are trying to solve. PHP arrays are a swiss army knife and the 2D variety are excellent for solving problems where you need to store variable, complex data elements.
Your question is very broad so I'll cover the two possibilities that come to mind:
1 > You're looking for a way to have PHP access and use multidimensional arrays:
$sData[0] = array("Name" => "T-Rex", "Type" => "dinosaur");
$sData[1] = array("Name" => "Frog", "Type" => "amphibian");
$sData[2] = array("Name" => "Salamander", "Type" => "amphibian);
This will allow you to have multiple rows with multiple sub-rows worth of data inside of them. There's no limit (besides machine memory) as to how many rows deep you can go.
2 > You're trying to figure out how to store that information in the database. In which case you need two tables like such:
Table: types
Structure: id INT(8) autoincrement, typename VARCHAR(65)
Example Data: 0, dinosaur -- 1, amphibian
Table: animals
Structure: id INT(8) autoincrement, type_id INT(8), name VARCHAR(65)
Example Data: 0, 0, T-Rex -- 1, 1, Frog -- 2, 1, Salamander

What is the order of foreach loop in PHP?

I have an array, for example
$arr=array(
"foo" => "fooval",
"boo" => "booval",
"roo" => "rooval",
);
and then I want to print all elements in pattern "key is value". This code should do the job:
foreach($arr as $key => $val)
echo $key." is ".$val;
Will I get this?
foo is fooval
boo is booval
roo is rooval
I mean the order. Is it guaranteed that it will execute in same order as the array was given, or the arrays are sorted somehow?
Thanks for any answers.
It will loop through the array in sequential order. So in your specific question you would see the results you expect.
arrays are ordered list of values and thier orders do not need to be sorted. It follows a sequence
FROM PHP DOC
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.

How does PHP keep track of order in an associative array?

When pushing a new value onto an indexed array
$array[] = 'new value';
the PHP documentation explains how it gets added in the [MAX_INDEX+1] position.
When pushing a new value onto an associative array
$array['key'] = 'new value';
it works the same, but I don't see any explanation in the documentation to confirm how or why it does so. The order seems to be consistent in my implementation, but how do I know for sure that the order will remain the same? Does anyone know how PHP implements this on the back-end?
All PHP Arrays, numeric and associative, are implemented as a so-called "Ordered Hash-Table". This is a data science term which amounts to: "A reasonable fast key-value store that keeps track of the order in which keys and values were inserted". In other words, PHP arrays have a bit of memory bolted on for the purpose of remembering order. Every time you put something in it, PHP automatically puts the order in there as well.
Interestingly, this happens for numeric keys as well- so if you put the values 1,2,3,4,5 into a PHP array, PHP is still separately keeping track of the order. If this sounds wasteful, that's because it is! It does, however, save brain cycles, that can be used to solve other poeple's problems, real and imagined.
MAX_INDEX actually has nothing to do with ordering.
you can do
$array[5] = 'new value';
$array[1] = 'new value';
$array[105] = 'new value';
$array[2] = 'new value';
and this array will keep that order as well.
PHP array is an ordered map, so, it's a map that keeps the order.
array elements just keep the order since they were added
that's all.
How are associative arrays implemented in PHP? might give you some insight.
It seems that PHP arrays are essentially hash tables, so the order of the array will stay the same until you reorder it (e.g. by sorting the array).
EDIT: It appears this is getting downvoted, allow me to explicitly include the sources I linked to in the comment below here...
"PHP associative arrays are in fact an implementation of HashTables", from
How is the PHP array implemented on the C level?
Also from that source: "The PHP array is a chained hash table (lookup of O(c) and O(n) on key collisions) that allows for int and string keys. It uses 2 different hashing algorithms to fit the two types into the same hash key space."
"Everything is a HashTable" from http://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html
I prefer to rely on ksort. In my experience, arrays stay consistent until you start removing elements. Better to manually sort them and know they're in the order you want.

fastest way to get parent array key in multidimensional arrays with php

what is the best way to get parent array key with multidimensional arrays?
for example I have this array:
array(
[0] => array(0=> sample, 1=>picture, 2=>frame, 3=>google)
[1] => array(0=> iphone, 1=>orange, 2=>love, 3=>msn)
[2] => array(0=> joe, 1=>geee, 2=>panda, 3=>yahoo)
)
now I need to search for example google and get the parent array key..
which it should be 0...any ideas? I used for loop for this but I think it will be slow if I have arrays with 700000 rows..
If you have an array with 700,000 rows you are almost certainly doing something wrong... I would first recomend thinking about utilizing a different data store: flat file or some type of DB.
foreach($array as $key => $value) {
if(in_array('google', $value)) return $key
}
Arrays with 700,000 rows? How many arrays? 9/10 times problem is that you've got your data set up wrongly.
I'm going to go ahead and assume you're doing a search of some sort. As you can't index an array (in the search meaning of index) then you're probably best putting the data into a database and making the most of column indexing to search fast.
Depending on context, you may alternatively want to think about storing your data in files, one per array, and using file searches to find which file contains your value.

Categories