| Start | ||||||||
|---|---|---|---|---|---|---|---|---|
| Applying a function to each element of an array To apply a function to every item in an array, use
Instead of using an anonymous function (opens new window), you could use a named function. The above could be written like: If the named function is a class method the call of the function has to include a reference to a class object the method belongs to: Another way to apply a function to every item in an array is The value parameter of the callback may be passed by reference, allowing you to change the value directly in the original array:
For nested arrays, Note: |
||||||||
| Split array into chunks array_chunk() (opens new window) splits an array into chunks Let's say we've following single dimensional array, Now using array_chunk() on above PHP array, Above code will make chunks of 2 array elements and create a multidimensional array as follow. If all the elements of the array is not evenly divided by the chunk size, last element of the output array will be remaining elements. If we pass second argument as less then 1 then E_WARNING will be thrown and output array will be NULL.
|
||||||||
| Imploding an array into string
Imploding keys can be done using Imploding keys with values is more complex but can be done using functional style: |
||||||||
| array_reduce
Usage:
Sum of array result: The largest number in array result: Is all item more than 100 result: Is any item less than 100 result: Like implode($array, $piece) result: if make a implode method, the source code will be : result: |
||||||||
| "Destructuring" arrays using list() Use list() (opens new window) to quick assign a list of variable values into an array. See also compact() (opens new window) With PHP 7.1 (currently in beta) you will be able to use short list syntax (opens new window): |
||||||||
| Push a Value on an Array There are two ways to push an element to an array: The array_push (opens new window) is used like this: This code will print:
This code will print: |
Read Article
https://develop.horje.com/learn/1434/reference