{"id":22344229,"url":"https://github.com/hi-folks/array","last_synced_at":"2026-02-08T22:07:43.538Z","repository":{"id":41837065,"uuid":"437128232","full_name":"Hi-Folks/array","owner":"Hi-Folks","description":"Arr class is built on top of the PHP array functions. Arr exposes methods for creating, managing, accessing to the array data structure.","archived":false,"fork":false,"pushed_at":"2025-06-17T00:25:58.000Z","size":371,"stargazers_count":16,"open_issues_count":3,"forks_count":9,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-03T03:03:38.424Z","etag":null,"topics":["array","hacktoberfest","php"],"latest_commit_sha":null,"homepage":"https://packagist.org/packages/hi-folks/array","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Hi-Folks.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"Hi-Folks"}},"created_at":"2021-12-10T22:17:07.000Z","updated_at":"2025-05-12T22:05:39.000Z","dependencies_parsed_at":"2024-05-28T01:56:23.465Z","dependency_job_id":"536c0f7b-7d6f-4700-86d6-8c520fc8b805","html_url":"https://github.com/Hi-Folks/array","commit_stats":{"total_commits":230,"total_committers":12,"mean_commits":"19.166666666666668","dds":0.5695652173913044,"last_synced_commit":"ace0186591cd6a9bc52b8c86627d9b0a24741655"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":"spatie/package-skeleton-php","purl":"pkg:github/Hi-Folks/array","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hi-Folks%2Farray","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hi-Folks%2Farray/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hi-Folks%2Farray/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hi-Folks%2Farray/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Hi-Folks","download_url":"https://codeload.github.com/Hi-Folks/array/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hi-Folks%2Farray/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263250595,"owners_count":23437288,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["array","hacktoberfest","php"],"created_at":"2024-12-04T09:09:10.250Z","updated_at":"2026-02-08T22:07:43.531Z","avatar_url":"https://github.com/Hi-Folks.png","language":"PHP","funding_links":["https://github.com/sponsors/Hi-Folks"],"categories":[],"sub_categories":[],"readme":"# Package array\n\n![PHP Array package](https://raw.githubusercontent.com/Hi-Folks/array/main/cover-arr.png)\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/hi-folks/array.svg?style=for-the-badge)](https://packagist.org/packages/hi-folks/array)\n[![PHP Unit Tests](https://img.shields.io/github/actions/workflow/status/hi-folks/array/run-tests.yml?branch=main\u0026style=for-the-badge)](https://github.com/Hi-Folks/array/actions)\n[![Total Downloads](https://img.shields.io/packagist/dt/hi-folks/array.svg?style=for-the-badge)](https://packagist.org/packages/hi-folks/array)\n\nThis package provides 2 classes:\n\n- **[Arr](#arr-class)** class is built on top of the PHP array functions.\n- **[Table](#table-class)** class allow you to manage bidimensional associative array (like a table or tuple).\n\n## Arr class\n\n**Arr** exposes methods to create, manage, access the data structure of the array.\n\nThe interface (method names, method arguments) are pretty similar to the Javascript Array class.\n\nI built this class because comparing method functions arrays of Javascript and PHP i think (my personal thought) that the JS one is smoother and has a good developer experience (but, again, it's a personal opinion).\n\nThe Arr class provides some methods:\n- make() create array;\n- fromFunction(): create Arr from a function;\n- fromValue(): create Arr from a value;\n- length(): length/size of the array;\n- arr(): returns data with the type PHP array\n- get(): get the element by index\n- getArr(): get the element (as Arr::class instance) by index (helpful for nested arrays)\n- Iterator methods: current(), next(), prev(), key(), valid(), rewind()\n- forEach(): execute a function for each element;\n- push(): add new element (at the end);\n- pop(): remove an element (at the end);\n- unshift(): add new element at the start;\n- shift(): remove an element from the start;\n- append(): append arrays to the current one;\n- concat(): return new array joining more arrays, Arr objects or scalar variables;\n- join(): joins all elements into a string;\n- slice(): returns a sub array;\n- indexOf(): find the first occurrence;\n- lastIndexOf(): find the last occurrence;\n- every(): all elements match a fn();\n- some(): at least one element matches a fn();\n- filter(): filter elements by a fn();\n- map(): apply a fn() for each element;\n- flat(): flat an array of arrays;\n- flatMap(): map() and flat();\n- fill(): fill an array (or a piece of an array);\n- reduce(): calculate a fn() with the array as input;\n- reduceRight(): like reduce(), but parsing the array in reverse order;\n- reverse(): reverse the array;\n- sort(): sort the array;\n- splice(): changes content of arr removing, replacing and adding elements;\n- toString(): the string representing the array (same as join(','));\n- isArray(): check if the input is an array;\n- from(): for creating new Arr from a string or array-like object;\n- findIndex(): for finding the index of some element;\n- find(): returns the first element in the array that satisfies the testing function;\n- entries(): returns a new Arr object that contains the key/value pairs for each index in the array;\n- copyWithin(): copies part of the array to a location but keeps the original length.\n- isEmpty(): checks if provided array is empty or not;\n- values(): it creates a new Arr object with the values of the current one (keys are skipped)\n- set(): ability to set an element to the array with a specific key\n- unset(): ability to unset an element by the key\n\n### The `get()` method\nThe `get()` method supports keys/indexes with the dot (or custom) notation for retrieving values from nested arrays.\nFor example:\n\n```php\n$fruits = Arr::make([\n    'green' =\u003e [\n        'kiwi' =\u003e '🥝',\n        'mango' =\u003e '🥭'\n    ],\n    'red' =\u003e [\n        'strawberry' =\u003e '🍓',\n        'apple' =\u003e '🍎'\n    ],\n    'yellow' =\u003e [\n        'lemon' =\u003e '🍋',\n        'banana' =\u003e '🍌',\n    ]\n]);\n$fruits-\u003eget('red'); // 🍓,🍎\n$fruits-\u003eget('red.strawberry'); // 🍓\n```\n\nYou can customize the notation with a different character:\n\n```php\n$fruits-\u003eget('red#strawberry', charNestedKey: '#'); // 🍓\n```\nYou can define a default value in the case the key doesn't exist:\n\n```php\n$fruits-\u003eget('red#somestrangefruit',\n'🫠', '#'); // 🫠\n```\n\n### The `getArr()` method\nIf you need to manage a complex array (nested array), or an array obtained from a complex JSON structure, you can access a portion of the array and obtain an Arr object.\nJust because in the case of a complex array the `get()` method could return a classic array.\n\nLet's see an example:\n\n```php\n    $arr = Arr::make(\n        [\n            \"avocado\" =\u003e\n                [\n                    'name' =\u003e 'Avocado',\n                    'fruit' =\u003e '🥑',\n                    'wikipedia' =\u003e 'https://en.wikipedia.org/wiki/Avocado'\n                ],\n            \"apple\" =\u003e\n                [\n                    'name' =\u003e 'Apple',\n                    'fruit' =\u003e '🍎',\n                    'wikipedia' =\u003e 'https://en.wikipedia.org/wiki/Apple'\n                ],\n            \"banana\" =\u003e\n                [\n                    'name' =\u003e 'Banana',\n                    'fruit' =\u003e '🍌',\n                    'wikipedia' =\u003e 'https://en.wikipedia.org/wiki/Banana'\n                ],\n            \"cherry\" =\u003e\n                [\n                    'name' =\u003e 'Cherry',\n                    'fruit' =\u003e '🍒',\n                    'wikipedia' =\u003e 'https://en.wikipedia.org/wiki/Cherry'\n                ],\n        ]\n    );\n$appleArr = $arr-\u003egetArr(\"apple\")\n// $appleArr is an Arr instance so that you can access\n// to the Arr methods like count()\n$arr-\u003egetArr(\"apple\")-\u003ecount();\n\n```\n### The `set()` method\nThe `set()` method supports keys with the dot (or custom) notation for setting values for nested arrays.\nIf a key doesn't exist, the `set()` method will create a new key and will set the value.\nIf a key already exists, the `set()` method will replace the value related to the key.\n\nFor example:\n\n```php\n$articleText = \"Some words as a sample sentence\";\n$textField = Arr::make();\n$textField-\u003eset(\"type\", \"doc\");\n$textField-\u003eset(\"content.0.content.0.text\", $articleText);\n$textField-\u003eset(\"content.0.content.0.type\", \"text\");\n$textField-\u003eset(\"content.0.type\", \"paragraph\");\n```\n\nSo when you try to set a nested key as \"content.0.content.0.text\", it will be created elements as a nested array.\nSo if you try to dump the value of the array of `$textField` you will see the following structure:\n\n```\nvar_dump($textField-\u003earr());\n\narray(2) {\n  [\"type\"]=\u003e\n  string(3) \"doc\"\n  [\"content\"]=\u003e\n  array(1) {\n    [0]=\u003e\n    array(2) {\n      [\"content\"]=\u003e\n      array(1) {\n        [0]=\u003e\n        array(2) {\n          [\"text\"]=\u003e\n          string(31) \"Some words as a sample sentence\"\n          [\"type\"]=\u003e\n          string(4) \"text\"\n        }\n      }\n      [\"type\"]=\u003e\n      string(9) \"paragraph\"\n    }\n  }\n}\n```\n\n## Table class\nTable class allows you to manage bi-dimensional array, something like:\n```\n[\n    ['product' =\u003e 'Desk', 'price' =\u003e 200, 'active' =\u003e true],\n    ['product' =\u003e 'Chair', 'price' =\u003e 100, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 300, 'active' =\u003e false],\n    ['product' =\u003e 'Bookcase', 'price' =\u003e 150, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 100, 'active' =\u003e true],\n]\n```\n\nEach row within the Table will be of type `Arr` so it allows you to lean on all the methods that\nare available via the `Arr` object.\n\n**Table class** allows you to filter, order, select some fields, create calculated fields.\nThe methods:\n- select(): select some fields\n- except(): exclude some fields\n- where(): filter data\n- groupBy(): grouping data into a Table of Tables, with an optional key mode (`GroupByKeyMode::VarExport`, `GroupByKeyMode::Strval`, `GroupByKeyMode::Int`)\n- transform(): transforms a specific field with the provided function\n- orderBy(): sorting data (ascending or descending)\n- toArray(): transform Table object into a native PHP array\n- toJson(): convert Table object into a JSON string\n\n\n`Table` now implements `\\Countable` and `\\Iterator`, this allows you to count the number of rows\nand also loop over the rows using common loops.\n\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require hi-folks/array\n```\n\n\n## Usage\n\nTo see some examples, I suggest you to take a look to *examples/cheatsheet.php* file,where you can see a lot of example and use cases.\n\nTo start quickly\n```php\n// Load the vendor/autoload file\nrequire(\"./vendor/autoload.php\");\n// import the Arr class:\nuse HiFolks\\DataType\\Arr;\n// use static make method to create Arr object\n$arr = Arr::make();\n$arr-\u003epush('Hi');\n$arr-\u003epush('Folks');\necho $arr-\u003elength();\n// to access to the \"native\" PHP array:\nprint_r($arr-\u003earr());\n```\nTo create an array with random values:\n```php\nrequire(\"./vendor/autoload.php\");\nuse HiFolks\\DataType\\Arr;\n$arr = Arr::fromFunction(fn () =\u003e random_int(0, 100), 500);\n```\n\nYou can access to the elements like a native array, but you have also Arr methods:\n```php\nrequire(\"./vendor/autoload.php\");\nuse HiFolks\\DataType\\Arr;\n$arr = Arr::make();\n$arr[] = \"First element\";\n$arr[] = \"Second element\";\n$count = $arr-\u003elength();\n// output: 2\n$arr-\u003ereverse();\necho $arr[0];\n// output: Second element\n```\n## Usage of Table class\n\nStarting from:\n\n```\n[\n    ['product' =\u003e 'Desk', 'price' =\u003e 200, 'active' =\u003e true],\n    ['product' =\u003e 'Chair', 'price' =\u003e 100, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 300, 'active' =\u003e false],\n    ['product' =\u003e 'Bookcase', 'price' =\u003e 150, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 100, 'active' =\u003e true],\n]\n```\nI would like to **filter** the rows with price greater than 100, **select** only \"product\" and \"price\" fields, and for each rows **create a new field** named \"new_filed\" that is a calculated field (doubling the price):\n```php\nuse HiFolks\\DataType\\Table;\n$dataTable = [\n    ['product' =\u003e 'Desk', 'price' =\u003e 200, 'active' =\u003e true],\n    ['product' =\u003e 'Chair', 'price' =\u003e 100, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 300, 'active' =\u003e false],\n    ['product' =\u003e 'Bookcase', 'price' =\u003e 150, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 100, 'active' =\u003e true],\n];\n$table = Table::make($dataTable);\n$arr = $table\n    -\u003eselect('product' , 'price')\n    -\u003ewhere('price', \"\u003e\", 100)\n    -\u003ecalc('new_field', fn ($item) =\u003e $item['price'] * 2);\n```\n\nThe result is\n```\nHiFolks\\DataType\\Table::__set_state(array(\n   'rows' =\u003e\n  array (\n    0 =\u003e\n    HiFolks\\DataType\\Arr::__set_state(array(\n       'arr' =\u003e\n      array (\n        'product' =\u003e 'Desk',\n        'price' =\u003e 200,\n        'new_field' =\u003e 400,\n      ),\n    )),\n    1 =\u003e\n    HiFolks\\DataType\\Arr::__set_state(array(\n       'arr' =\u003e\n      array (\n        'product' =\u003e 'Door',\n        'price' =\u003e 300,\n        'new_field' =\u003e 600,\n      ),\n    )),\n    2 =\u003e\n    HiFolks\\DataType\\Arr::__set_state(array(\n       'arr' =\u003e\n      array (\n        'product' =\u003e 'Bookcase',\n        'price' =\u003e 150,\n        'new_field' =\u003e 300,\n      ),\n    )),\n  ),\n))\n```\n\n### Grouping data with `groupBy()`\n\nThe `groupBy()` method groups rows by a field value and returns a **Table of Tables**. You can then use `get()` to access each group by its key and drill into the rows:\n\n```php\nuse HiFolks\\DataType\\Table;\n\n$table = Table::make([\n    ['product' =\u003e 'Desk', 'price' =\u003e 200, 'active' =\u003e true],\n    ['product' =\u003e 'Chair', 'price' =\u003e 100, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 300, 'active' =\u003e false],\n    ['product' =\u003e 'Bookcase', 'price' =\u003e 150, 'active' =\u003e true],\n    ['product' =\u003e 'Door', 'price' =\u003e 100, 'active' =\u003e true],\n]);\n\n$grouped = $table-\u003egroupBy('product');\n$grouped-\u003ecount(); // 4 groups: Desk, Chair, Door, Bookcase\n\n$deskItems = $grouped-\u003eget('Desk');\n$deskItems-\u003ecount(); // 1\n\n$doorItems = $grouped-\u003eget('Door');\n$doorItems-\u003ecount(); // 2\n\n$firstDoor = $doorItems-\u003efirst();\n$firstDoor-\u003eget('price');   // 300\n$firstDoor-\u003eget('product'); // 'Door'\n$firstDoor-\u003eget('active');  // false\n```\n\nBecause `groupBy()` returns a Table, you can chain it with `where()` and `orderBy()` to build powerful queries. For example, to get the cheapest active product in each group:\n\n```php\n$cheapest = $table\n    -\u003ewhere('active', '=', true)\n    -\u003eorderBy('price', 'asc')\n    -\u003egroupBy('product');\n\n$cheapest-\u003eget('Door')-\u003efirst()-\u003eget('price'); // 100\n```\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [Roberto B.](https://github.com/roberto-butti)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhi-folks%2Farray","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhi-folks%2Farray","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhi-folks%2Farray/lists"}