Download the PHP package itools/smartarray without Composer
On this page you can find all versions of the php package itools/smartarray. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download itools/smartarray
More information about itools/smartarray
Files in itools/smartarray
Package smartarray
Short Description Enhanced PHP arrays with built-in HTML encoding and chainable collection methods
License MIT
Homepage https://github.com/interactivetools-com/SmartArray
Informations about the package smartarray
SmartArray: Enhanced Arrays with Chainable Methods and Automatic HTML Encoding
SmartArray extends PHP arrays with automatic HTML encoding and chainable utility methods. It adds powerful features for filtering, mapping, and data manipulation - making common array operations simpler, safer, and more expressive.
Table of Contents
- SmartArray: Enhanced Arrays with Chainable Methods and Automatic HTML Encoding
- Table of Contents
- Quick Start
- Usage Examples
- Highlighting Recent Articles with position()
- Accessing Elements by Position with nth()
- Looking Up Authors by ID with indexBy()
- Organizing Books by Genre with groupBy()
- Extracting Unique Tags with pluck(), unique(), and implode()
- Building Dynamic HTML Tables with sprintf()
- Creating Grid Layouts with isFirst() and isLast()
- Debugging and Help
- Method Reference
- Questions?
Quick Start
Install via Composer:
Include the Composer autoloader and SmartArray class:
Convert an array to a SmartArray and use the recommended workflow:
See the Method Reference for more information on available methods.
Usage Examples
Highlighting Recent Articles with position()
The position() method returns an element's position within its parent array (starting from 1), making it easy to give
special treatment to important items like featured articles based on their position:
Accessing Elements by Position with nth()
The nth() method provides a convenient way to access elements by their position, supporting both positive and negative
indices. This is particularly useful for accessing specific items in ordered lists like search results, leaderboards, or
recent activity feeds.
Key Features:
- Zero-based indexing:
nth(0)returns the first element - Negative indices:
nth(-1)returns the last element - Works with both indexed and associative arrays
Looking Up Authors by ID with indexBy()
When working with collections of records, you often need to look up specific records by their ID or another unique
field. The indexBy() method makes this easy by creating an associative array using a specified field as the key:
Output:
Important Notes:
- If multiple records have the same key value, later records will overwrite earlier ones
- For collections with duplicate keys, use
groupBy()instead to preserve all records- Keys are automatically converted to strings (as per PHP array key behavior)
- Missing keys in the source data will be skipped with a warning
Need to preserve duplicate keys? Consider using groupBy() instead.
Organizing Books by Genre with groupBy()
When working with data that has multiple items sharing the same key (like books by genre, products by category, or
employees by department), groupBy() helps organize them into logical groups while preserving all records:
Output:
Common Use Cases for groupBy():
- Products by category or manufacturer
- Employees by department or location
- Sales by region or time period
- Students by grade level or class
- Events by date or venue
- Comments by post or user
- Tasks by status or priority
Important Notes:
- Each group contains a new SmartArray of all matching records
- Original record order is preserved within groups
- Groups are created in order of first appearance
- Missing or null values in the group key will be skipped with a warning
- Use
indexBy()instead if you only need one record per key
Extracting Unique Tags with pluck(), unique(), and implode()
When working with collections, you often need to extract a single field, remove duplicates, and produce a display
string.
Here's how SmartArray chains these operations into a single expressive pipeline.
Building Dynamic HTML Tables with sprintf()
The sprintf() method applies formatting to each element, making it easy to wrap values in HTML tags.
Combined with implode(), you can build table rows in a single expression.
Key Features:
- Supports
{value}and{key}as readable aliases for%1$sand%2$s - Also works with standard sprintf formats:
%s,%1$s,%2$s, etc. - Values are automatically HTML-encoded for SmartArrayHtml (XSS-safe)
- Format string is applied to each element, then
implode()joins them
Output:
Note how O'Connor, <script>, and & are safely HTML-encoded in the output.
Using {key} for Select Options:
Output:
Creating Grid Layouts with isFirst() and isLast()
SmartArray provides isFirst() and isLast() methods for position-based operations, making it easy to add
opening and closing markup around iterated elements:
Debugging and Help
SmartArray provides helpful debugging tools to inspect your data structures and explore available methods.
Debug View
Call print_r() on any SmartArray to see a detailed view of its structure:
The output shows the nested structure and metadata:
Interactive Help
Need a quick reference? Call help() on any SmartArray object to see available methods
and usage examples:
Method Reference
Note: All methods return a new SmartArray object unless otherwise specified.
| Category | Method | Description |
|---|---|---|
| Creation & Conversion | SmartArray::new($array) | Create a SmartArray with raw PHP values for data processing. Arrays become SmartArrays, missing keys become SmartNulls |
| $array->toArray() | Converts back to regular PHP array with original values | |
| $array->asHtml() | Return values as HTML-safe SmartString objects (lazy conversion - returns same object if already HTML-safe) | |
| $array->asRaw() | Return values as raw PHP types (lazy conversion - returns same object if already using raw values) | |
| SmartArrayHtml::new($array) | Create a SmartArray with HTML-safe SmartString values directly (equivalent to SmartArray::new()->asHtml()) | |
| Value Access | $obj->key | Get a value using property syntax |
| get(key) | Get a value by key (for numeric keys or keys with special characters) | |
| get(key, default) | Get a value with optional default if key not found | |
| set(key, value) | Set a value by key (for numeric keys or keys with special characters) | |
| first() | Get the first element | |
| last() | Get the last element | |
| nth(index) | Get element by position, ignoring keys (0=first, -1=last) | |
| SmartArray::getRawValue($value) | Converts SmartArray and SmartString objects to their original values while leaving other types unchanged | |
| Array Information | count() | Get the number of elements |
| isEmpty() | Returns true if array has no elements | |
| isNotEmpty() | Returns true if array has any elements | |
| contains(value) | Returns true if array contains value | |
| Position & Layout | isFirst() | Returns true if first element in parent array |
| isLast() | Returns true if last element in parent array | |
| position() | Gets position in parent array (starting from 1) | |
| Sorting & Filtering | sort() | Sorts elements by value (flat arrays only) |
| sortBy(field) | Sorts rows by field value (nested arrays only) | |
| unique() | Removes duplicate values (flat arrays only) | |
| filter() | Removes falsey values ("", 0, empty array, etc) | |
| filter(callback) | Removes elements where callback returns false (callback receives raw values) | |
| where(field, value) | Keeps rows where field matches value (uses loose comparison: '1' matches 1, false matches 0). Chain for multiple conditions. | |
| whereNot(field, value) | Excludes rows where field matches value (inverse of where) | |
| whereInList(field, value) | Filters rows where tab-delimited field contains value | |
| Array Transformation | toArray() | Converts back to regular PHP array with original values |
| keys() | Gets array of keys, discarding the values | |
| values() | Gets array of values, discarding the keys | |
| indexBy(field) | Indexes rows by field value, latest is kept if duplicates | |
| groupBy(field) | Groups rows by field value, preserving duplicates | |
| pluck(valueField, keyField) | Gets array of field values from rows, optionally indexed by another field | |
| pluckNth(index) | Gets array of values at position from rows | |
| implode(separator) | Joins elements with separator into string | |
| sprintf(format) | Applies sprintf formatting to each element. Supports {value} and {key} placeholders. |
|
| map(callback) | Transforms each element using callback (callback receives raw values) | |
| each(callback) | Call callback on each element as Smart objects. Used for side effects, doesn't modify array. | |
| merge(...$arrays) | Merges with one or more arrays. Numeric keys are renumbered, string keys are overwritten by later values. | |
| column(columnKey, indexKey) | Mirrors PHP's array_column(). Calls pluck() or indexBy() internally. |
|
| Database Operations | The following optional methods may be available when using SmartArray with database results | |
| mysqli() | Get an array of all mysqli result metadata (set when creating array from DB result) | |
| mysqli(key) | Get specific mysqli result metadata (errno, error, affected_rows, insert_id, etc) | |
| load(field) | Loads related record(s) for field using load handler | |
| Error Handling | or404(message) | Exits with 404 header and message if array is empty, default: "The requested URL was not found on this server." |
| orDie(message) | Exits with message if array is empty | |
| orThrow(message) | Throws exception with message if array is empty | |
| orRedirect(url) | Redirects to URL if array is empty (HTTP 302) | |
| Debugging and Help | help() | Displays help information about available methods |
| debug() | Show content of object as well as properties | |
| print_r($obj) | Show array contents of object (useful for debugging) |
See Also: For working with SmartArrayHtml values, check out the included companion
library SmartString. SmartArrayHtml values are SmartString objects with
automatic HTML encoding and chainable methods:
https://github.com/interactivetools-com/SmartString?tab=readme-ov-file#method-reference
Questions?
This library was developed for CMS Builder, post a message in our "CMS Builder" forum here: https://www.interactivetools.com/forum/