I want to modify the way to iterate an SPLObjectStorage object, such as sorting it first by the data (info).
So, in a loop, it goes numerically from a to z (using sort() function)
But, in SPLObjectStorage, there is no access to the array, right ?
Is it possible to do it since we don't have the access to the array of objects ??
No, it's not possible. Internally SplobjectStorage use the same data structure as an array (the HashTable), but it's not an "array-array" as we know from the PHP userland: we only add values and not keys, as keys are actually generated from the values by hashing them (you can even overwrite this by overwriting the getHash method). Another difference is that you can additionally add information to the object.
In short, SplObjectStorage should not be used as an array, but as either a set or a map, there lies its strength.
Related
foreach in PHP7 by default, when iterating by value, operates on a copy of the array according to: http://php.net/manual/en/migration70.incompatible.php
Does it lazily create a copy only if there are changes made to the array or a value or will it always make a copy and in essence make looping over references a performance optimization?
Also, do arrays of objects still loop over/give you references of the objects? Or will they actually also create copies for the foreach and return the objects by value?
In PHP 7, if you iterate an array by value, the copy will be done lazily, only when and if the array is actually modified.
If you iterate an array by reference instead, a separation will be performed at the start of the loop. If the array is currently used in more than one place, this separation will lead to a copy.
Furthermore iterating by reference means that a) the array has to be wrapped into a reference and b) each element has to be wrapped in a reference as well. Creating a reference wrapper is an expensive operation, because it requires allocation.
Additionally iteration by reference requires us to use a modification-safe iteration mechanism. This works by registering the iterator with the array and checking for potentially affected iterators in various array modification operations.
So no, iterating by reference is certainly not an optimization, it's a de-optimization. Using references usually is.
Might not be a question specific to Eloquent collections, but it just hit me while working with them. Let's just assume we have a $collection object which is an instance of Illuminate\Support\Collection.
Now if we want to iterate over it, what are the pros and cons of using each() with a closure versus a regular foreach. Are there any?
foreach ($collection as $item) {
// Some code
}
versus
$collection->each(function ($item) {
// Some code
});
A foreach statement should be used as a sort of a way to cycle through a collection and perform some sort of logic on it. If what is in it effects other things in the program, then use this loop.
The .each method uses array_map to cycle through each of the objects in the collection and perform a closure on each one. It then returns the resulting array. That is the key! .each should be used if you want to change the collection in some way. Maybe it's an array of cars and you want to make the model upper case or lower case. You would just pass a closure to the .each method that takes the object and calls strtoupper() on the model of each Car object. It then returns the collection with the changes that have been made.
Morale of the story is this: use the .each method to change each item in the array in some way; use the foreach loop to use each object to affect some other part of the program (using some logic statement).
UPDATE (June 7, 2015)
As stated so Eloquently (see what I did there?) below, the above answer is slightly off. The .each method using array_map never actually used the output from the array_map call. So, the new array created by array_map would not be saved on the Collection. To change it, you're better off using the .map method, which also exists on a Collection object.
Using a foreach statement to iterate over each of them makes a bit more sense because you won't be able to access variables outside the Closure unless you make sure to use a use statement, which seems awkward to me.
The implementation when the above answer was originally written can be found here.
.each in Laravel 5.1
The new .each that they are talking about below no longer uses array_map. It simply iterates through each item in the collection and calls the passed in $callback, passing it the item and its key in the array. Functionally, it seems to work the same. I believe using a foreach loop would make more sense when reading the code. However, I see the benefits of using .each because it allows you to chain methods together if that tickles your fancy. It also allows you to return false from the callback to leave the loop early if your business logic demands you to be able to.
For more info on the new implementation, check out the source code.
There is a lot of confusing misinformation in the existing answers.
The Short Answer
The short answer is: There is no major difference between using .each() vs. foreach to iterate over a Laravel collection. Both techniques achieve the same result.
What about modifying items?
Whether or not you're modifying items is irrelevant to whether you use .each() vs. foreach. They both do (and don't!) allow you to modify items in the collection depending on what type of items we're talking about.
Modifying items if the Collection contains objects: If the Collection is a set of PHP objects (such as an Eloquent Collection), either .each() or foreach allow you to modify properties of the objects (such as $item->name = 'foo'). That's simply because of how PHP objects always act like references. If you're trying to replace the entire object with a different object (a less common scenario), use .map() instead.
Modifying items if the Collection contains non-objects: This is less common, but if your Collection contains non-objects, such as strings, .each() doesn't give you a way to modify the values of the collection items. (The return value of the closure is ignored.) Use .map() instead.
So... which one should I use?
In case you're wondering about performance, I did several tests with large collections of both Eloquent items and a collection of strings. In both cases, using foreach was faster than .each(). But we're talking about microseconds. In most real-life scenarios the speed difference wouldn't be significant compared to the time it takes to access the database, etc.
It mostly comes down to your personal preference. Using .each() is nice because you can chain several operations together (for example .where(...).each(...)). I tend to use both in my own code just depending on what seems the cleanest for each situation.
Contrary to what the two other answers say, Collection::each() does not change the values of the items in the Collection, technically speaking. It does use array_map(), but it doesn't store the result of that call.
If you want to modify each item in a collection (such as to cast them to objects as Damon in a comment to the crrently accepted answer), then you should use Collection::map(). This will create a new Collection based on the result of the underlying call to array_map().
It is more beneficial to use the latter: each().
You can chain conditions and write clearer more expressive code, eg:
$example->each()->map()->filter();
This takes you closer to Declarative Programming where you tell the computer what to accomplish instead of how to accomplish.
Some useful articles:
https://martinfowler.com/articles/collection-pipeline/
https://adamwathan.me/refactoring-to-collections/
->each() is the same as foreach(...) but worse.
The main difference here is Variable scope.
In classical foreach you can easily operate variables declared before the foreach. If you are dealing with closure, you would need to inheriting variables from the parent scope with use. This feature is confusing, because when you use it, your function becomes scope dependant...
You can chain ->each() with other functions, but since it does not change the values in the collection, it has very limited use case. And because it is "rare to use", it is not always easily recognizable by developers when they read your code.
Not many people will read your code, cherish those who will.
The foreach() construct does not allow you to change the value of the array item being iterated over, unless you pass the array by reference.
foreach ($array as &$value) $value *= $value;
The each() eloquent method wraps the PHP array_map() function, which allows this.
Like the previous answer states, you should use foreach() if you have any other motivation. This is because the performance of foreach() is much better than array_map().
http://willem.stuursma.name/2010/11/22/a-detailed-look-into-array_map-and-foreach/
The PHP documentation states:
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
AFAIK, PHP arrays are ordered hash-maps. So, why is it per se forbidden to use objects as keys, is there a reason for this limitation? Why is there no possibility to implement a hash function in a class in order to use it as a key?
On a related note, is there a PHP implementation of a hash-map which solves this issue?
Keys need to be immutable in order for them to work. If your objects are mutable, then they can't be keys. That's true in every language that implements them: Java, C#, etc.
See #duffymo for the answer.
Note that there is a "workaround" of sorts, by using spl_object_hash as your key. This returns a string, which is immutable, that can be used as a key and will be the same for any object which occupies that memory address. (Read: spl_object_hash will return the same value for the same instance regardless of where it's called or if the object has changed)
The PHP function json_decode (by default) returns an object. Switching the second argument will return an array.
Maybe I just don't understand objects, but I thought objects have properties and methods (maybe events too). Arrays only have properties.
Given that json_decode will only ever return properties and never methods, shouldn't it always return an array?
It returns an object because JSON defines an object structure. This is what the 'O' stands for in 'JSON'.
This is where the differences between languages starts to become more obvious.
Javascript uses objects where PHP might use an array with named keys. JS can't have named keys in an array, only in an object. Other languages have other limitations to how they structure their variables.
Using an object means that PHP is as consistent with other language implementations of JSON as possible. Since JSON is designed for cross-language communication, being consistent is important.
But as you say, in PHP it is sometimes easier to work with an array, so this is why PHP offers the option of converting it directly to an array.
But be aware that PHP arrays are not the same as JSON arrays and objects. PHP allows you to mix named and numbered array keys. This does not map well to JSON, so if you're using PHP arrays to work with JSON you have to be careful of it. If you're using PHP objects for your JSON work, then you won't have this mismatch in functionality.
Okay, so it seems you already knew this:
By default, json_decode will return a StdClass object. If you want an array, use:
json_decode($jsondata, true);
See: http://php.net/manual/en/function.json-decode.php
So, to answer "Why":
JSON is a format used to store hierachical datasets, much like how XML might have been used in the past. Because however Javascript is optimized for accessing object properties, no additional libraries need be present to work with JSON structures - they are actual objects in Javascript.
It is easier to parse JSON than XML, and relatively easy to translate into objects and/or arrays in back-end languages. In many languages outside of PHP, there is something called a Dictionary, or Hashtable, which is usually an object with key/value pairs.
PHP does not differentiate arrays and "associative arrays" other than contextually, so for a PHP developer it's natural to expect the result to be an associative array, and that option exists, but most likely for flexibility (and maybe because it decodes more naturally to the object) the object format exists.
I hope that explains. I also strongly recommend reading further on what JSON is (and is not) here:
http://json.org
json_decode returns by default an object from the stdClass class. This is the basic (top-level) generic class for objects. This class has no method nor attributes first.
But then you can add some "on the fly", what's called Dynamic Properties. More here:
Sometimes all that is necessary is a property bag to throw key value pairs into. One way is to use array, but this requires quoting all keys. Another way is to use dynamic properties on an instance of StdClass.
Hope it helps.
It returns the object of stdClass.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.
I'm working on code to manage a collection of unique objects. The first prototype of this code utilises an associative array, basically as that's the way I've always done it.
However, I'm also keen on taking advantage of functionality that's been added to more modern versions of PHP such as [SplObjectStorage][1] for doing this instead, partly as a learning experience, partly because it's bound to offer advantages (benchmarks I've seen suggest that SplObjectStorage can be faster than arrays in a lot of cases).
The current implementation has an associative array that I check with in_array() to see if an object is already in the array before adding a new object to it.
The big problem I can see with SplObjectStorage is that it doesn't seem (at first glance) to support key/value associative array behaviour, and can only be treated as an indexed array. However, the documentation for the newer features of PHP isn't up to the standards of the documentation of more established parts of the language and I might simply be missing something.
Can I use SplObjectStorage in place of an associative array? If so, how do I define the key when adding a new object? More importantly, what are the relative advantages and disadvantages of SplObjectStorage when compared to associative arrays?
You shouldn't see the SplObjectStorage as a key-value store, but merely a set of objects. Something is in the set or not, but its position is not important.
The "key" of an element in the SplObjectStorage is in fact the hash of the object. It makes it that it is not possible to add multiple copies of the same object instance to an SplObjectStorage, so you don't have to check if a copy already exists before adding.
However, in PHP 5.4 there is a new method called getHash() which you can override that will return the "hash" of the object. This - in a sense - returns/set the key so you can allow it to store under different conditions.
The main advantage of SplObjectStorage is the fact that you gain lots of methods for dealing and interacting with different sets (contains(), removeAll(), removeAllExcept() etc). Its speed is marginally better, but the memory usage is worse than normal PHP arrays.
Results after running this benchmark with 10,000 iterations on PHP 5.6.13:
Type
Time to fill
Time to check
Memory
SplObjectStorage
0.021285057068
0.019490000000
2131984
Array
0.021125078201
0.020912000000
1411440
Arrays use 34% less memory and are about the same speed as SplObjectStorage.
Results with PHP 7.4.27:
Type
Time to fill
Time to check
Memory
SplObjectStorage
0.019295692444
0.016039848328
848384
Array
0.024008750916
0.022011756897
3215416
Arrays use 3.8 times more memory and are 24% slower than SplObjectStorage.
Results with PHP 8.1.1:
Type
Time to fill
Time to check
Memory
SplObjectStorage
0.009704589844
0.003775596619
768384
Array
0.014604568481
0.012760162354
3215416
Arrays use 4.2 times more memory and are 50% slower than SplObjectStorage.
When all the memory allocated to array is used up, the memory allocated to it will be doubled. In this context, a collection of objects may be more effective structure.