Splice V Collection

0 views
Skip to first unread message

Arnaude Kubiak

unread,
Aug 5, 2024, 11:23:16 AM8/5/24
to sinnatorot
Asphari has pointed out, the collection is read-only. If you want a way to omit a certain range of items from any array-like object (similar to splice() but without modifying the original collection), you can do the following.

If you need this behavior you have to write it on your one, but maybe you can simply wrap one of the above. But you should define what happens if the user defines a greater number than elements available or a number of zero or less.


If the number of spliced elements is bigger then the number of elements in a list then GetRange() and RemoveRange() methods throw an exception. The better solution is to use Skip() and Take() and check for List size:


The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. For example, check out the following code. We'll use the collect helper to create a new collection instance from the array, run the strtoupper function on each element, and then remove all empty elements:


As you can see, the Collection class allows you to chain its methods to perform fluent mapping and reducing of the underlying array. In general, collections are immutable, meaning every Collection method returns an entirely new Collection instance.


Collections are "macroable", which allows you to add additional methods to the Collection class at run time. The Illuminate\Support\Collection class' macro method accepts a closure that will be executed when your macro is called. The macro closure may access the collection's other methods via $this, just as if it were a real method of the collection class. For example, the following code adds a toUpper method to the Collection class:


For the majority of the remaining collection documentation, we'll discuss each method available on the Collection class. Remember, all of these methods may be chained to fluently manipulate the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:


afterallaverageavgbeforechunkchunkWhilecollapsecollectcombineconcatcontainscontainsOneItemcontainsStrictcountcountBycrossJoindddiffdiffAssocdiffAssocUsingdiffKeysdoesntContaindotdumpduplicatesduplicatesStricteacheachSpreadensureeveryexceptfilterfirstfirstOrFailfirstWhereflatMapflattenflipforgetforPagegetgroupByhashasAnyimplodeintersectintersectAssocintersectByKeysisEmptyisNotEmptyjoinkeyBykeyslastlazymacromakemapmapIntomapSpreadmapToGroupsmapWithKeysmaxmedianmergemergeRecursiveminmodemultiplynthonlypadpartitionpercentagepipepipeIntopipeThroughpluckpopprependpullpushputrandomrangereducereduceSpreadrejectreplacereplaceRecursivereversesearchselectshiftshuffleskipskipUntilskipWhilesliceslidingsolesomesortsortBysortByDescsortDescsortKeyssortKeysDescsortKeysUsingsplicesplitsplitInsumtaketakeUntiltakeWhiletaptimestoArraytoJsontransformundotunionuniqueuniqueStrictunlessunlessEmptyunlessNotEmptyunwrapvaluevalueswhenwhenEmptywhenNotEmptywherewhereStrictwhereBetweenwhereInwhereInStrictwhereInstanceOfwhereNotBetweenwhereNotInwhereNotInStrictwhereNotNullwhereNullwrapzip


This method searches for the given item using "loose" comparison, meaning a string containing an integer value will be considered equal to an integer of the same value. To use "strict" comparison, you may provide the strict argument to the method:


The chunkWhile method breaks the collection into multiple, smaller collections based on the evaluation of the given callback. The $chunk variable passed to the closure may be used to inspect the previous element:


The contains method determines whether the collection contains a given item. You may pass a closure to the contains method to determine if an element exists in the collection matching a given truth test:


The contains method uses "loose" comparisons when checking item values, meaning a string with an integer value will be considered equal to an integer of the same value. Use the containsStrict method to filter using "strict" comparisons.


The countBy method counts the occurrences of values in the collection. By default, the method counts the occurrences of every element, allowing you to count certain "types" of elements in the collection:


The diff method compares the collection against another collection or a plain PHP array based on its values. This method will return the values in the original collection that are not present in the given collection:


The diffAssoc method compares the collection against another collection or a plain PHP array based on its keys and values. This method will return the key / value pairs in the original collection that are not present in the given collection:


The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on array_diff_uassoc, which is the PHP function that the diffAssocUsing method utilizes internally.


The diffKeys method compares the collection against another collection or a plain PHP array based on its keys. This method will return the key / value pairs in the original collection that are not present in the given collection:


The doesntContain method determines whether the collection does not contain a given item. You may pass a closure to the doesntContain method to determine if an element does not exist in the collection matching a given truth test:


You may also call the firstOrFail method with no arguments to get the first element in the collection. If the collection is empty, an Illuminate\Support\ItemNotFoundException exception will be thrown:


The flatMap method iterates through the collection and passes each value to the given closure. The closure is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by one level:


In this example, calling flatten without providing the depth would have also flattened the nested arrays, resulting in ['iPhone 6S', 'Apple', 'Galaxy S7', 'Samsung']. Providing a depth allows you to specify the number of levels nested arrays will be flattened.


The forPage method returns a new collection containing the items that would be present on a given page number. The method accepts the page number as its first argument and the number of items to show per page as its second argument:


The implode method joins items in a collection. Its arguments depend on the type of items in the collection. If the collection contains arrays or objects, you should pass the key of the attributes you wish to join, and the "glue" string you wish to place between the values:


By converting the collection to a LazyCollection, we avoid having to allocate a ton of additional memory. Though the original collection still keeps its values in memory, the subsequent filters will not. Therefore, virtually no additional memory will be allocated when filtering the collection's results.


The mapSpread method iterates over the collection's items, passing each nested item value into the given closure. The closure is free to modify the item and return it, thus forming a new collection of modified items:


The mapToGroups method groups the collection's items by the given closure. The closure should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:


The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given item's value will overwrite the value in the original collection:


The mergeRecursive method merges the given array or collection recursively with the original collection. If a string key in the given items matches a string key in the original collection, then the values for these keys are merged together into an array, and this is done recursively:


You may pass an integer to random to specify how many items you would like to randomly retrieve. A collection of items is always returned when explicitly passing the number of items you wish to receive:


The reduceSpread method reduces the collection to an array of values, passing the results of each iteration into the subsequent iteration. This method is similar to the reduce method; however, it can accept multiple initial values:


The replace method behaves similarly to merge; however, in addition to overwriting matching items that have string keys, the replace method will also overwrite items in the collection that have matching numeric keys:


The search is done using a "loose" comparison, meaning a string with an integer value will be considered equal to an integer of the same value. To use "strict" comparison, pass true as the second argument to the method:


If there are no elements in the collection that should be returned by the sole method, an \Illuminate\Collections\ItemNotFoundException exception will be thrown. If there is more than one element that should be returned, an \Illuminate\Collections\MultipleItemsFoundException will be thrown.


The sort method sorts the collection. The sorted collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:


If your sorting needs are more advanced, you may pass a callback to sort with your own algorithm. Refer to the PHP documentation on uasort, which is what the collection's sort method calls utilizes internally.


The sortBy method sorts the collection by the given key. The sorted collection keeps the original array keys, so in the following example we will use the values method to reset the keys to consecutively numbered indexes:


If you would like to sort your collection by multiple attributes, you may pass an array of sort operations to the sortBy method. Each sort operation should be an array consisting of the attribute that you wish to sort by and the direction of the desired sort:


The callback must be a comparison function that returns an integer less than, equal to, or greater than zero. For more information, refer to the PHP documentation on uksort, which is the PHP function that sortKeysUsing method utilizes internally.

3a8082e126
Reply all
Reply to author
Forward
0 new messages